Php 如何在Laravel 5.4中返回透视表中的所有值
我有一张透视表,包括 帐号 第11条 创建于 更新地址 如何检索视图中的所有对象。我有两个模型帐户和文章Php 如何在Laravel 5.4中返回透视表中的所有值,php,model,laravel-5.4,Php,Model,Laravel 5.4,我有一张透视表,包括 帐号 第11条 创建于 更新地址 如何检索视图中的所有对象。我有两个模型帐户和文章 class Account extends Model { public function articles() { return $this->belongsToMany('App\Article','accountsarticles')->withPivot('account_id','article_id')->withTimesta
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
我想知道如何检索该透视中的所有列,以便在返回视图时显示该列中的所有数据。使用以下语法$model->pivot->field\u name 在您的情况下,它将是:
//to fetch account id
$article->pivot->account_id
//to fetch article id
$article->pivot->article_id
我已经尝试过了,但它让我尝试获取非object的属性。您并没有在视图中发送模型集合。您正在使用DB仅从表名$ACCOUNTARTICLES=DB::table'ACCOUNTARTICLES'->get获取数据,这就是它给出错误的原因。@Student将$acc=Account::所有数据发送到视图。我已经更改为$acc,但没有返回帐户id和文章id。甚至我已经使用了pivot->field\名称。仅在返回的位置创建和更新了\u您试图在视图中显示什么?特定账户的物品@大学生