framework icon indicating copy to clipboard operation
framework copied to clipboard

has() on a hasOne()-relationship to the same table

Open mruoss opened this issue 12 years ago • 3 comments

Hi there

I posted this already to the forum but I reckon this is a bug in the implementation of laravel. I therefore repost it as an issue here on github:

Consider the following setup (and let's not discuss wether it makes sense as it's only an example). I have a class person, in the db I have a field husband_person_id. If it is set, it means the person is the wife of some other person which is her husband:

class Person {
  function husband() {
    return $this->belongsTo('Person', 'husband_person_id'); 
  }
  function wife() {
    return $this->hasOne('Person', 'husband_person_id');
  }
}

Now I want to get a list with all people that are not husbands i.e. have no wife:

$non_husbands = Person::has('wife', '=', 0)->get();

However, this doesn't work. The has() function inside the query builder creates an sql query as follows and join it to the select query of persons:

select count(*) from `persons` where `persons`.`husband_person_id` = `persons`.`id`;

I would expect something like this:

select count(*) from `persons` p2 where `p2`.`husband_person_id` = `persons`.`id`;

I see this as a bug in laravel. Am I wrong? Is there a way to achieve what I want?

Thanks a lot!

Cheers, Michael

mruoss avatar Apr 09 '14 10:04 mruoss

As pointed out in the forum, there is a workaround to this. However, a native implementation of has() using aliases would be much better.

The workaround

Person::has('wife', '<', 1, 'and', function ($q) {
    $q->from( DB::raw('people wifes') )
        ->orWhereRaw( 'people.id = wifes.husband_id' );
    })->get();

mruoss avatar Apr 09 '14 11:04 mruoss

If you see a way to make this easier feel free to make a pull request. The whereHas method make your implementation a little less verbose.

taylorotwell avatar Apr 11 '14 14:04 taylorotwell

Most of the relations, Illuminate\Database\Eloquent\Relations\ *, have a function getRelationCountQuery. These functions return this:

return $query->where($this->getQualifiedForeignKey(), '=', new Expression($otherKey));

But for self referencing relations the table needs to be aliased. Something like this:

    $parentTable = $this->getParent()->getTable();
    $relatedTable = $this->getRelated()->getTable();
    $qForeignKey = $this->getQualifiedForeignKey();
    $otherKey = $this->getOtherKey();
    if($parentTable == $relatedTable) {
      $query->from($parentTable.' as '.$parentTable.'2');
      $query->whereRaw($qForeignKey.' = '.$parentTable.'2.'.$otherKey);
      return $query;

marshnmedia avatar Oct 08 '14 15:10 marshnmedia