亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel Eloquent 從一個表中選擇并在另一個表中有匹配項時加入第一行

Laravel Eloquent 從一個表中選擇并在另一個表中有匹配項時加入第一行

PHP
素胚勾勒不出你 2023-03-04 18:08:22
我有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 的用戶的結果,并將最新的評論附加到該結果。我可以$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 中有很多結果,它會很慢
查看完整描述

2 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

使用帶有自定義查詢的預加載:


User::with(['comments' => function($query){

  $query->latest();

}])->where('first_name','bob')->get();


查看完整回答
反對 回復 2023-03-04
?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

額外的關系可以解決問題。


public function latestComment()

{

    return $this->hasOne(Comment::class)->latest('date');

}

現在您可以使用$user->latestComment.


查看完整回答
反對 回復 2023-03-04
  • 2 回答
  • 0 關注
  • 140 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號