Laravel Eloquent hasMany condition in parent table

Viewed 7940

I have these tables:

  1. places
    • id
    • name
    • address
  2. users
    • id
    • name
    • email
  3. reviews
    • id
    • place_id
    • user_id
    • title
    • review
    • as_anoniem

The user_id is filled even if as_anoniem is 1.

Now I want to have all the reviews for all the places with the user except for the ones with as_anoniem = 1.

Something like this:

Place::with(['review' => function ($query) {
    return $query->with('user')->where('as_anoniem', 1);
}]);

This is not fully correct as it returns only reviews with as_anoniem = 1.

How can I achieve this using ?

3 Answers

It is possible to use values of model in conditions:

class Content extends Model
{

    // ...

    /**
     * Get linked content
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function linked()
    {
        return $this->hasMany(self::class, 'source_content_id', 'source_content_id')
            ->where('source_content_type_id', '=', $this->source_content_type_id)
            ->where('id', '<>', $this->id);
    }
}

You can check out this link https://stackoverflow.com/a/18600698/16237933.

class Game extends Eloquent {
    // many more stuff here

    // relation without any constraints ...works fine 
    public function videos() {
        return $this->hasMany('Video');
    }

    // results in a "problem", se examples below
    public function available_videos() {
        return $this->videos()->where('available','=', 1);
    }
}
Related