Peter February 2016

How add to collection only models with no record joined - Eloquent

In my model Questions I have simple relation to Standpoint

public function standpoints_byrel()
{
//    return $this->hasMany('App\Models\Standpoint');
return $this->hasMany('App\Models\Standpoint',  'question_id');

}

Now, I have yet another model Userattitude (tableuser_attitudes`) which allow users to upvote and downvote Standpoints.

I am able to list Standpoints, which were voted by a given user:

    $user_attitudes = Userattitude::join('entitystandpoints', function ($q) use($questionid,$user) {
        $q->where('user_attitudes.item_type', '=', 'entitystandpoint');
        $q->on('user_attitudes.item_id', '=', 'entitystandpoints.id');
        $q->where('entitystandpoints.question_id', '=', $questionid);
        $q->where('user_attitudes.creator_id','=', $user);
    })
    ->select('user_attitudes.*')
    ->get();

TO DO

Now I try to list all standpoints, which were NOT voted by the given user. I have no idea how to do it using Eloquent. Any help appreciated.

edit

condition to meet: if an user votes up or down, a new model Userattitude is created. Therefore Standpoint models not down- or upvoted have nothing to join. still, in the Userattitude there are two fields for upvoting : 'attitude' and 'importance'. often one of them is null

Answers


Paolof76 February 2016

Try with a left join where the left parameter of the join is null. Something like this (but please check the syntax out, I'm not an Eloquent expert):

   $user_attitudes = Userattitude::leftJoin('entitystandpoints', function ($q) use($questionid,$user) {
        $q->where('user_attitudes.item_type', '=', 'entitystandpoint');
        $q->on('user_attitudes.item_id', '=', 'entitystandpoints.id');
        $q->where('entitystandpoints.question_id', '=', $questionid);
        $q->where('user_attitudes.creator_id','=', $user);
    })
    ->whereNull('entitystandpoints.id')
    ->select('user_attitudes.*')
    ->get();

Let me know.

Post Status

Asked in February 2016
Viewed 2,102 times
Voted 12
Answered 1 times

Search




Leave an answer