[英]Laravel select records with pivot table
I have a little problem with eloquent. I have 3 tables.我对 eloquent 有点问题。我有 3 个表。
Users
, phrases
, and phrase_user
. Users
、 phrases
和phrase_user
用户。 phrase user contains columns: id, phrase_id, user_id
I need to select phrases with pivot table for example. phrase user 包含列:
id, phrase_id, user_id
我需要 select phrases with pivot table 例如。 This action with SQL will be like this... SQL 的这个动作将是这样的......
SELECT phrase FROM phrases
LEFT JOIN phrase_user ON phrases.id = phrase_user.phrase_id
LEFT JOIN users ON phrase_user.user_id = $userId
This is my index function in controller这是我在 controller 中的索引 function
$phrases = DB::table('phrases')->orderBy('id','desc')->Paginate(5);
$user = Auth::user();
return view('pages.phrases.index')->with(['phrases' => $phrases, 'user' => $user]);
I also have written these functions in models... Phrase model:我也在模型中写了这些功能......短语model:
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
User model:用户model:
public function phrases()
{
return $this->belongsToMany('App\Phrase')->withTimestamps();
}
In this case, paginator is not working properly because $phrases = DB::table('phrases')->orderBy('id','desc')->Paginate(5);
在这种情况下,paginator 无法正常工作,因为
$phrases = DB::table('phrases')->orderBy('id','desc')->Paginate(5);
There is some problem..有点问题..
In conclusion: I need to show only my phrases in phrases page.总之:我只需要在短语页面中显示我的短语。 every user must have their phrases.
每个用户都必须有自己的短语。
Try using lowercase paginate尝试使用小写分页
$phrases = DB::table('phrases')->orderBy('id','desc')->paginate(5);
$userId = 2;
$phrases = DB::table('phrases')->whereHas('users', function ($q) use ($userId) {
$q->whereId($userId);
})->orderBy('id','desc')->Paginate(5);
$user = Auth::user();
return view('pages.phrases.index')->with(['phrases' => $phrases, 'user' => $user]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.