首页 > 解决方案 > Laravel Eloquent 3 表连接查询

问题描述

我有 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- share.host = $someUserId 和 share.guest_answer = 1。

3- share.guest = $someUserId 和 share.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 的事件。

非常感谢您的时间。

标签: phplaraveleloquent

解决方案


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

推荐阅读