问题
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