[英]Eloquent - Having problems using eager loading on nested relationships
I'm trying to eager load nested relationships, but I'm having trouble returning the correct results.我正在尝试急切加载嵌套关系,但无法返回正确的结果。
Here are the models:以下是模型:
User.php用户名
class User extends Model
{
public function universities()
{
return $this->hasMany('\StudentApp\Models\UserUniversity');
}
}
UserUniversity.php用户大学.php
class UserUniversity extends Model
{
protected $fillable = [ 'user_id', 'university_id', 'choice' ];
public function university()
{
return $this->hasOne('\StudentApp\Models\University');
}
}
University.php大学.php
class University extends Model
{
protected $table = 'university';
}
What I want to do is get a user by ID, fetch the users universities from the UserUniversity
pivot table, and then fetch the name of that university from the University
table.我想要做的是通过 ID 获取用户,从UserUniversity
数据透视表中获取用户大学,然后从University
表中获取该大学的名称。
I've tried the following to test if it works:我尝试了以下方法来测试它是否有效:
$user = User::with('universities')->find($this->jwtObject->uid);
return $response->withJson($user->universities[0]->university);
But I get the following error:但我收到以下错误:
Column not found: 1054 Unknown column 'university.user_university_id' in 'where clause' (SQL: select * from `university` where `university`.`user_university_id` = 10 and `university`.`user_university_id` is not null limit 1) [] {"uid":"28c5a97"}
user.user_university_id
is incorrect. user.user_university_id
不正确。 That column doesn't exist and I'm not sure why it's trying to use that column.该列不存在,我不确定为什么要尝试使用该列。
What it should be using is user.university_id
它应该使用的是user.university_id
How can I do this?我怎样才能做到这一点?
You should add foreign key and primary key in relation:您应该在关系中添加外键和主键:
public function universities()
{
return $this->hasMany('\StudentApp\Models\University', 'university_id', 'id');
}
Correct nested eager loading syntax is:正确的嵌套预加载语法是:
User::with('universities.university')
Also, make sure you've using the correct foreign key in the university
table:另外,请确保您在university
表中使用了正确的外键:
user_university_id
Or define another key in the relationship:或者在关系中定义另一个键:
public function university()
{
return $this->hasOne('\StudentApp\Models\University', 'another_foreign_key');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.