我有2張桌子+----+------------+------------+| id | first_name | date |+----+------------+------------+| 1 | Bob | 01/01/2019 |+----+------------+------------+| 2 | June | 01/05/2019 |+----+------------+------------+和+----+--------+---------+------------+| id | userID | comment | date |+----+--------+---------+------------+| 1 | 1 | Hello | 02/01/2019 |+----+--------+---------+------------+| 2 | 1 | Again | 02/02/2019 |+----+--------+---------+------------+| 3 | 2 | Howdy | 02/03/2019 |+----+--------+---------+------------+我想獲得所有名字為 Bob 的用戶的結(jié)果,并將最新的評(píng)論附加到該結(jié)果。我可以$users = SELECT * FROM Users WHERE id = 1然后foreach($users as $user){ $comment = Comment::where("userID", $user->id)->first(); if($comment != null){ $user->comments = $comment->$comment; }}但是,如果 $users 中有很多結(jié)果,它會(huì)很慢
2 回答

開(kāi)滿天機(jī)
TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
使用帶有自定義查詢的預(yù)加載:
User::with(['comments' => function($query){
$query->latest();
}])->where('first_name','bob')->get();

德瑪西亞99
TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
額外的關(guān)系可以解決問(wèn)題。
public function latestComment()
{
return $this->hasOne(Comment::class)->latest('date');
}
現(xiàn)在您可以使用$user->latestComment.
- 2 回答
- 0 關(guān)注
- 139 瀏覽
添加回答
舉報(bào)
0/150
提交
取消