Laravel雄辩的3表联接查询

时间:2018-08-24 20:59:33

标签: php laravel eloquent

我有3个移民

默认用户迁移,事件迁移和共享迁移。

Schema::create('events', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('owner');
        $table->dateTime('start_date');
        $table->dateTime('end_date');
        $table->dateTime('alert_date');
        $table->string('title');
        $table->text('description');
        $table->string('local');
        $table->timestamps();

        $table->foreign('owner')->references('id')->on('users');
    });

Schema::create('shares', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('host');
        $table->unsignedInteger('guest');
        $table->boolean('host_answer')->nullable();
        $table->boolean('guest_answer')->nullable();;
        $table->timestamps();

        $table->foreign('host')->references('id')->on('users');
        $table->foreign('guest')->references('id')->on('users');
    });

然后我在各个模型上建立了关系。

用户:

public function events()
{
    return $this->hasMany(Event::class);
}

public function host()
{
    return $this->hasMany(Share::class);
}

public function guest()
{
    return $this->hasMany(Share::class);
}

事件:

public function userOwner()
{
    return $this->belongsTo(User::class, 'owner');
}

分享:

public function userGuest()
{
    return $this->belongsTo(User::class, 'guest');
}

我需要满足至少三个条件之一的所有不同事件:

1- events.owner = $ someUserId。

2-shares.host = $ someUserId,shares.guest_answer = 1。

3-shares.guest = $ someUserId,shares.guest_answer = 1。

如果这只是SQL,我想我可以进行查询...但是是laravel,所以我在查询时遇到了一些麻烦。

这就是我得到的:

 $events = Event::join('users', 'events.owner', '=', 'users.id')
                ->join('shares', 'users.id', '=', 'shares.host')
                ->where  ([[ 'events.owner', $userId ]])
                ->orWhere([[ 'shares.host', $userId],
                           [ 'shares.guest_answer', '1' ]])
                ->orWhere([[ 'shares.guest', $userId],
                           [ 'shares.guest_answer', '1' ]])
                ->paginate(10);

但是此查询只是返回其中events.owner = $ userId的事件。

非常感谢您的时间。

1 个答案:

答案 0 :(得分:0)

    $userId = Auth::id();

    $events = Event::join('users'       , 'events.owner', '=', 'users.id')
                   ->join('shares as sg', 'users.id'    , '=', 'sg.guest')
                   ->join('shares as sh', 'users.id'    , '=', 'sh.host' )

                   ->Where([   ['events.owner'    , '=', $userId] ])

                   ->orWhere([ ['sg.host'         , '=', $userId] ,
                               ['sg.guest_answer' , '=', '1']     ])

                   ->orWhere([ ['sh.guest'        , '=', $userId] ,
                               ['sh.guest_answer' , '=', '1']     ])

                    ->paginate(10);