gpt4 book ai didi

php - 我如何急切加载最新记录,其中每条记录都具有特定列的不同值?

转载 作者:行者123 更新时间:2023-12-04 16:06:45 24 4
gpt4 key购买 nike

假设我有一张名为messages

的表
+----+--------------+-------------+-----+
| ID | user_id | conv_id |body |
+----+--------------+-------------+-----+
|1..5| 1 | 1 | ... |
+----+--------------+-------------+-----+
| 6 | 1 | 3 | ... |
+----+--------------+-------------+-----+
| 7 | 1 | 3 |... |
+----+--------------+-------------+-----+
| 8 | 1 | 1 |... |
+----+--------------+-------------+-----+
| 9 | 1 | 2 |... |
+----+--------------+-------------+-----+
| 10 | 1 | 1 | ... |
+----+--------------+-------------+-----+
| 11 | 1 | 2 |... |
+----+--------------+-------------+-----+
| 12 | 1 | 4 |... |
+----+--------------+-------------+-----+
| 13 | 1 | 5 |... |
+----+--------------+-------------+-----+
| 14 | 1 | 4 |... |
+----+--------------+-------------+-----+

我想输出这个结果:

+----+--------------+-------------+-----+
|2..5| 1 | 1 | ... |
+----+--------------+-------------+-----+
| 10 | 1 | 1 | ... |
+----+--------------+-------------+-----+
| 7 | 1 | 3 | ... |
+----+--------------+-------------+-----+
| 11 | 1 | 2 | ... |
+----+--------------+-------------+-----+
| 13 | 1 | 5 |... |
+----+--------------+-------------+-----+
| 14 | 1 | 4 |... |
+----+--------------+-------------+-----+

作为预先加载的结果。如您所见,它输出 5 个最新记录,其中 conv_id = 1 加上每个其他 conv_id 的最新记录。我该怎么做?


这是我的 Controller 代码和我尝试过的代码

$loginuser = User::find(Auth::user()->id);

//$allOpenConvMsgs is an array of 5 message IDs where `conv_id = 1`.
//The relationship between user and messages is many-to-many.
See model codes below

$newMessages = $loginuser->messages()->where(function($q){
$q->where(''); //I'm stuck here!
})->orWhereIn('messages.id',$allOpenConvMsgs);

消息模型

public function user(){
return $this->belongsToMany('User');
}

用户模型

public function messages(){
return $this->belongsToMany('Messages');
}

最佳答案

如果我明白你的意思,你可以这样做:

$loginuser = User::find(Auth::user()->id)->with(array('messages' => function($q){
$q->where('conv_id', '=', '1')->take(5)->orderBy('id', 'desc');
})->get();

$newMessages = $loginuser->messages;

更新

根据 David 的建议,最好使用通过 Auth::user() 函数获取的 User 实例。

所以上面的代码将是:

$newMessages = Auth::user()->load(array('messages' => function($q){
$q->where('conv_id', '=', '1')->take(5)->orderBy('id', 'desc');
}))->messages;

更新 2

上面的代码只获取conv_id = 1的消息,要获取所有最近的消息你必须移除where条件:

$newMessages = Auth::user()->load(array('messages' => function($q){
$q->take(5)->orderBy('id', 'desc');
}))->messages;

关于php - 我如何急切加载最新记录,其中每条记录都具有特定列的不同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24884096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com