Reputation: 1076
Yii2 build relation many to many
I have 2 tables users and friends
Code query
$friends = Friends::find()
->select(['friends.user_id', 'users.name'])
->leftJoin('users','users.id = friends.friend_user')
->with('users')
->all();
In result error
Invalid Parameter – yii\base\InvalidParamException. app\models\Friends has no relation named "users".
Upvotes: 0
Views: 220
Reputation: 18729
Friends
has a column called user_id
and thus only belongs to one user. If you auto-generated the Friends
ActiveRecord it probably has a function getUser
(singular because it is only one) that will look something like this:
public function getUser() {
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
So you're getting the error because no getUsers
function exists (that returns a valid ActiveQuery object). Because there can only be one user per friend I think you should use the singular version. And if that still gives the same error you should implement the function above and maybe change it a bit to match your classname.
When you use with(['relation'])
to load relations Yii will convert the entry to getRelation
and call that function on the model to get the query that is needed to load the relation.
Upvotes: 2