如何根据数据透视 table 中的值与 laravel 5.6 中必需的 table 中的值的比较来获取数据?
How to get data based in comparing value in pivote table with value in required table in laravel 5.6?
我正在学习 larvel 5.6,所以我试图在数据透视 table
中检索 ID 大于 last_seen_id 的消息数量
我的用户 table 具有由以下人员生成的默认列:
php artisan make:auth
和消息 table 具有以下列:
id, 来自, message_content, group_id
和组 table 具有以下列:
id,类型
现在用户和组之间存在多对多关系 table 通过自定义数据透视表 table 具有以下列:
group_id,user_id,last_id_seen
现在如果我想检索属于同一组且在数据透视表中具有比 last_id_seen 更大的 ID 的消息 table 怎么办?
我想你正在寻找这样的东西:
$groupId = 1; // set to whatever you want
$lastSeenId = \Auth::user()->groups()
->where('group_id', $groupId)
->first()->pivot->last_id_seen;
$messages = Message::where('id', '>', $lastSeenId)->get();
一个更强大的版本,当您的用户还没有该组的条目时不会失败,将是:
$groupId = 1; // set to whatever you want
$group = \Auth::user()->groups()->where('group_id', $groupId)->first();
$lastSeenId = $group ? $group->pivot->last_id_seen : null;
$messages = Message::when($lastSeenId, function($query, $id) {
$query->where('id', '>', $id);
})->get();
注意:通常您会在第二个代码段中使用 optional()
,但是 Laravel 5.2 不包含此帮助程序...
如果您想要 count()
结果和结果本身,您可以将查询存储在一个变量中并使用它执行两个查询。这样您就不必两次重写相同的查询:
$groupId = 1; // set to whatever you want
$group = \Auth::user()->groups()->where('group_id', $groupId)->first();
$lastSeenId = $group ? $group->pivot->last_id_seen : null;
$query = Message::when($lastSeenId, function($query, $id) {
$query->where('id', '>', $id);
});
$count = $query->count();
$messages = $query->get();
我正在学习 larvel 5.6,所以我试图在数据透视 table
中检索 ID 大于 last_seen_id 的消息数量我的用户 table 具有由以下人员生成的默认列:
php artisan make:auth
和消息 table 具有以下列:
id, 来自, message_content, group_id
和组 table 具有以下列:
id,类型
现在用户和组之间存在多对多关系 table 通过自定义数据透视表 table 具有以下列:
group_id,user_id,last_id_seen
现在如果我想检索属于同一组且在数据透视表中具有比 last_id_seen 更大的 ID 的消息 table 怎么办?
我想你正在寻找这样的东西:
$groupId = 1; // set to whatever you want
$lastSeenId = \Auth::user()->groups()
->where('group_id', $groupId)
->first()->pivot->last_id_seen;
$messages = Message::where('id', '>', $lastSeenId)->get();
一个更强大的版本,当您的用户还没有该组的条目时不会失败,将是:
$groupId = 1; // set to whatever you want
$group = \Auth::user()->groups()->where('group_id', $groupId)->first();
$lastSeenId = $group ? $group->pivot->last_id_seen : null;
$messages = Message::when($lastSeenId, function($query, $id) {
$query->where('id', '>', $id);
})->get();
注意:通常您会在第二个代码段中使用 optional()
,但是 Laravel 5.2 不包含此帮助程序...
如果您想要 count()
结果和结果本身,您可以将查询存储在一个变量中并使用它执行两个查询。这样您就不必两次重写相同的查询:
$groupId = 1; // set to whatever you want
$group = \Auth::user()->groups()->where('group_id', $groupId)->first();
$lastSeenId = $group ? $group->pivot->last_id_seen : null;
$query = Message::when($lastSeenId, function($query, $id) {
$query->where('id', '>', $id);
});
$count = $query->count();
$messages = $query->get();