I have 3 migration
Default User migration, Event migration and Share migration.
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');
});
Then i have the relationships established on the respective models.
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);
}
Event:
public function userOwner()
{
return $this->belongsTo(User::class, 'owner');
}
Share:
public function userGuest()
{
return $this->belongsTo(User::class, 'guest');
}
I need all distinct events where at least one of 3 conditions are meet:
1- events.owner = $someUserId.
2- shares.host = $someUserId and shares.guest_answer = 1.
3- shares.guest = $someUserId and shares.guest_answer = 1.
If this was simply SQL i guess i would be able to make the query... but is laravel so i'm having some troubles with my query.
This is what i get:
$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);
But this query is simply returning the events where events.owner = $userId.
Thank you very much for you time.
$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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.