在 Laravel 中使用 Eloquent 查询连接表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43297669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:45:27  来源:igfitidea点击:

Querying join tables with Eloquent in Laravel

laraveleloquentlaravel-eloquent

提问by Poorya

Im using Laravel Eloquent to make a join query. Here are my Models

我使用 Laravel Eloquent 进行连接查询。这是我的模型

My Queue Schema:

我的队列架构:

    $table->increments('id');

    $table->string('task');

    $table->string('qustatus');

    $table->boolean('inqueue');

    $table->integer('user_id')->index();

    $table->timestamps();

Queue Model

队列模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Queue extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

my User Schema:

我的用户架构:

$table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->string('fcmToken')->nullable();

User Model:

用户模型:

class User extends Authenticatable
{
    public function queues()
    {
        return $this->hasMany('App\Queue');
    }
}

here i'm trying to get the fcmTokenfor all the users with inqueueset to 1or trueI have tried to use '$queue = Queue::with('user')->get();' which returns the entire data. but failed to filter it or find any article with similar sample.

在这里,我正在尝试fcmToken为所有用户inqueue设置为,1或者true我尝试使用 '$queue = Queue::with('user')->get();' 它返回整个数据。但未能过滤它或找到任何具有类似样本的文章。

回答by Poorya

just in case anyone else is wondering, this is how i did it.

以防万一其他人想知道,我就是这样做的。

$queue = DB::table('queues')
            ->select(
                'queues.id',
                'queues.inqueue',
                'users.fcmToken'
            )
            ->join(
                'users',
                'users.id','=','queues.user_id'
            )
            ->where(['queues.inqueue' => true])
            ->get();