[英]Laravel BelongsToMany with array of ids as an attribute isntead of individual id
Given:鉴于:
"users" table:
[{
id: 1,
school_ids: [1, 2, 3] // text type cast as array
}]
Then:然后:
"schools" table:
[{
id: 1,
name: 'school 1",
},
{
id: 2,
name: 'school 2",
},
{
id: 3,
name: 'school 3",
}]
I currently have a relationship in my User model as:我目前在我的用户 model 中有一个关系:
public function schools() {
return $this->belongsToMany(School::class, 'school_ids');
}
which currently doent's work.目前没有工作。
school_ids
it will cast it as an array and calling User::schools()
will give me a collection of School
Model?我想知道我是否可以让它在哪里工作,如果它读取school_ids
它将把它转换为一个数组并调用User::schools()
会给我一个School
Model 的集合?By relation i guess you can't but you can make something like this通过关系,我想你不能,但你可以做这样的事情
public function schools() {
return Schools::whereIn('id',$this->school_ids)->get(); // Will return collection of Schools object
}
So to make my life easier, I decided to create a pivot table instead that links the school and user.因此,为了让我的生活更轻松,我决定创建一个 pivot 表来连接学校和用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.