laravel 4雄辩:一对多导致奇怪的结果

时间:2013-10-18 15:50:09

标签: laravel laravel-4

我在这里有一些非常奇怪的问题与laravel一对多关系。我在User和Book之间有一对多的关系。尝试从视图中显示相关对象时,结果为none或相关对象,具体取决于我访问它的方式。

用户模型

//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

1 个答案:

答案 0 :(得分: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