2013-10-18 66 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