我在这里遇到了一些关于 laravel 一对多关系的非常奇怪的问题。我在用户和书之间有一对多的关系。当尝试从视图中显示相关对象时,结果要么是无,要么是相关对象,具体取决于我如何访问它。
用户模型
//User table: id, username, ...
class User extends ConfideUser implements UserInterface, RemindableInterface {
public function books(){
return $this->hasMany("Book","user");
}
}
图书模型
//Book table: id, user, title...
class Book extends Ardent{
public function myUser(){
return $this->belongsTo("User","user"); //I name user_id field as "user"
}
}
看法:
@if( ! empty($book->myUser)) //It is always empty
@else
{{$book->myUser}} //It displays the user object
@endif
{{$book->myUser->id}} //ErrorException: Trying to get property of non-object
{{$book->myUser["id"]}} //This works