如何通过比较数据透视表中的值与laravel 5.6中所需表中的值来获取数据?

时间:2018-08-07 16:34:20

标签: laravel eloquent laravel-5.2

我正在学习larvel 5.6,因此我尝试检索ID大于数据透视表中的last_seen_id的消息数

我有一个用户表,该表具有由以下项生成的默认列:

php artisan make:auth

和具有以下列的邮件表:

id,来自message_content,group_id

和组表具有以下列:

id,type

现在,通过具有以下各列的自定义数据透视表,用户表和组表之间存在许多联系:

group_id,user_id,last_id_seen

现在是否要检索数据透视表中属于同一组且具有比last_id_seen更大的id的邮件?

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找这样的东西:

$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();