2013-10-18 42 views
0

我在这里有一些非常奇怪的问题与laravel一对多关系。我在用户和书籍之间有一对多的关系。当试图从视图中显示相关的对象时,结果是none或者相关的对象,这取决于我如何访问它。laravel 4雄辩:一对多导致奇怪的结果

用户模型

//User table: id, username, ... 
class User extends ConfideUser implements UserInterface, RemindableInterface { 
    public function books(){ 
     return $this->hasMany("Book","user"); 
    } 

} 

Book模型

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

你没有告诉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"); 
    } 
} 

您可以检查的关系,并得到结果使用(得到谁拥有的书(S)用户)

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

如果这样的查询

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

在您的view中,您可以使用

@foreach ($books as $book) 
    {{ $book->user->id }} 
@endforeach