2017-09-25 111 views
0

枢轴表中的所有值我得到了包括 ACCOUNT_ID 的article_id created_at 的updated_at如何返回Laravel 5.4

如何检索所有的人都在观透视表。我有2个型号的帐户和文章

class Account extends Model 
{ 
    public function articles() 
    { 
     return $this->belongsToMany('App\Article','accountsarticles')->withPivot('account_id','article_id')->withTimestamps(); 
    } 
} 

class Article extends Model 
{ 
    public function accounts() 
    { 
     return $this->belongsToMany('App\Account','accountsarticles')->withPivot('account_id','article_id')->withTimestamps(); 
    } 
} 

,也是我有控制器这样

class AccountsArticlesController extends Controller 
{ 
    public function index() 
    { 
     /*If i use this 1 i can get all of column data*/ 
     $accountsarticles=DB::table('accountsarticles')->get(); 

     /*If i use this 1 i only get created_at and updated_at*/ 
     $acc = Account::all(); 
     return view('accountsarticles.index',['accountsarticles'=>$accountsarticles]); 
    } 
} 

现在我找回它像这样不使用MVC

@foreach($accountsarticles as $article) 
    <tr> 
     <td>{{$article->created_at}}</td> 
     <td>{{$article->updated_at}}</td> 
     <td>{{$article->account_id}}</td> 
     <td>{{$article->article_id}}</td> 
    </tr> 
@endforeach 

我想知道如何检索该枢轴中的所有列,以便我可以在视图返回时显示该列中的所有数据。

回答

0

使用以下语法$model->pivot->field_name

在你的情况,这将是:

//to fetch account id 
$article->pivot->account_id 

//to fetch article id 
$article->pivot->article_id 
+0

我已经尝试,但它给我“试图获得非对象的财产” – Student

+0

你是不是在您的视图中发送模型的集合。你使用'DB'来从表名只提取数据'$ accountsarticles = DB :: table('accountsarticles') - > get()'这就是它给出错误的原因。 –

+0

@Student发送'$ acc = Account :: all()'数据到视图。 –