0

我在这里遇到了一些关于 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
4

1 回答 1

1

你没有讲课,ConfideUser但基本上应该扩展Eloquent

class User extends Eloquent implements UserInterface, RemindableInterface {

    public function books(){
        return $this->hasMany("Book","user"); // <-- assumed user is custom key
    }
}

模型相同Book,(您没有电话Ardent来自哪里以及如何实施)

class Book extends Eloquent{
    public function user(){
        return $this->belongsTo("User", "user");
    }
}

您可以使用(获取拥有书籍的用户)检查关系并获取结果

$books = Book::has('user')->get();

如果你这样查询

$books = Book::all();
return View::make('books')->with('books', $books);

在你的view你可以使用

@foreach ($books as $book)
    {{ $book->user->id }}
@endforeach
于 2013-10-18T19:43:17.467 回答