php - 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 的事件。
非常感谢您的时间。
解决方案
$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);
推荐阅读
- javascript - 垂直居中的图片行
- middleware - 为什么在 CKAN 中保存了这么多 Beaker 会话?
- linux - 如何在 ACPI 中声明多路复用器后面的设备?
- selenium - PHP webdriver 选择一个选项会留下另一个选项被选中
- unit-testing - 用于输入限制的 Angular 单元测试指令
- html - 将存储在 HTML5 localstorage 中的值相加
- docker - 如何在 Dockerfile 中将用户输入作为文本发送?
- node.js - 使用 Node.js 通过 SQLite 插入值时的主键问题
- c++ - 使用 static_cast 创建的枚举调用 C++ 函数的安全性
- python-3.x - 每当将新数据加载到 s3 存储桶中时如何触发 python 脚本?