Eloquent - using Union to combine two symmetric relationships throws error

不打扰是莪最后的温柔 提交于 2020-01-04 05:42:32

问题


I built a many-to-many relationship between users as friends through a pivot table. They have to have different foreign keys in the pivot (friends) table, user_from_id, user_to_id.

In the User model, I define two relationship:

public function friends_from() {
  return $this->belongsToMany('App\User,'friends',
   'user_from_id`, `user_to_id`);
}

... and friends_to symmetrically, which works fine.

But it still makes it hard to consolidate just all "my friends. I thought I found a really clever approach by combining them in a "friends" method and still have a builder, tried to do a union of the two relationship methods:

public function friends() {
  return $this->friends_to()->unionAll($this->friends_from());
}

But this generates an SQL exception:

Cardinality violation: 1222 The used SELECT statements have a different number of columns

The SQL:

select
`users`.*, `friends`.`user_from_id` as `pivot_user_from_id`,
`friends.user_to_id` as `pivot_user_to_id`
from `users`
inner join `friends`
on `users`.`id` = `friends`.`user_to_id`
where `friends`.`user_from_id` = 245)

union all 
(select * from `users` inner join `friends`
on `users`.`id` =           `friends`.`user_from_id`
where `friends`.`user_to_id` = 245)

So it looks close but I'm missing something essential. Any insights?

Thanks

来源:https://stackoverflow.com/questions/36637478/eloquent-using-union-to-combine-two-symmetric-relationships-throws-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!