Poorya
Poorya

Reputation: 1320

Querying join tables with Eloquent in Laravel

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

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 fcmToken for all the users with inqueue set to 1or true I 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.

Upvotes: 2

Views: 10541

Answers (1)

Poorya
Poorya

Reputation: 1320

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

Upvotes: 4

Related Questions