vendredi 15 février 2019

Create Customized Relationship?

The model user may have 0 or more foo's and may have 0 or more bar's. Here is a diagram:

enter image description here

There is the following rule: If a user has any bar, then this implies that he has the foo with id=1. A user may not have foo with id=1 without a bar. To prevent database inconsistency, there is never a row inserted in foo_user with foo_id = 1, because its already implied by the bar_user table.

In Laravel I can get all foo's from a user like this:

public foos()
{
    $this->hasMany('App\Foo');
}

The problem is that because of the above rule, the foo with id = 1 might be missing. Is there an easy way to customize my relationship method foos so that it checks, if bar_user exists, then add foo with id=1? I would like to get the correct foos with one query and with the relationship, so I may use this like \App\User::whereHas('foos', ...)


This is what I tried

The query to get all foo's is

  \DB::table('foos')
          ->leftjoin('foo_user', 'foo.id', 'foo_user.foo_id')
          ->where('foo_user.user_id', '=', $this->id);
          ->orWhereRaw('EXISTS (select * from bar_user WHERE user_id = ?) AND foos.id = 1', [$this->id]);

I cannot do

public foos()
{
    $this->hasMany('App\Foo')
         ->orWhereRaw('EXISTS (select * from bar_user WHERE user_id = ?) AND foos.id = 1', [$this->id]); 
}

because there is an innerjoin in hasMany and not a leftjoin.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire