How to select only one Column with scope of eloquent model?

Viewed 222

I got two tables. Both have a relationship to each other. I´m trying to query both to get the matching results. This results get checked if they also have an column which matches with a parameter value. I´m trying it with a scope and it work. I only need one column from the second table and I´m trying to use it as column in my first table when I got my result. So the code works and I got an result but I´m trying to filter to select only one column from the second table.

My code look like that.

My controller:

public function test()
 {
     
    $UID='LQuupgYvnuVzbEoguY4TF8bnHUU2';

    $event=Events::withState($UID)->get();
    echo $event;
 }

My model scope function:

public function scopeWithState($query,$UID){
    return $query->with(['EventLiked' => function($query) use($UID) {
        $query
        ->where('EventLiked.UID', $UID)
        ;
    }]);
}

My hasMany relationship function:

public function EventLiked()
{
    return $this->hasMany(EventLiked::class,'EID','ID')->select('State','UID','EID');
}
1 Answers

I would go for specifying columns inside closure.

New scope:

public function scopeWithState($query,$UID){
    return $query->with(['EventLiked' => function($query) use($UID) {
        $query
        ->where('EventLiked.UID', $UID)
        ->select('State');
    }]);
}

Calling scope:

$event=Events::withState($UID)->get();

You're not getting expected results because Laravel splits it into 2 queries:

  1. First, for selecting events.
  2. Then it plucks EID
  3. Second, when it looks for EventLiked where matching ID's is found (from second step) and loads as relationships.

So you want to change select statement only in 2nd query. Not in a first one

Related