Xun Yang
Xun Yang

Reputation: 4419

laravel 4 eloquent: one to many result in strange result

I'm having some really weird issues here with laravel one-to-many relation. I have a one-to-many relation between User and Book. When trying to display the related object from view, the result is either none or the related object depending on how I access it.

User model

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

}

Book model

//Book table: id, user, title... 
class Book extends Ardent{
    public function myUser(){
        return $this->belongsTo("User","user");  //I name user_id field as "user"
    }


}

view:

@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

Upvotes: 0

Views: 136

Answers (1)

The Alpha
The Alpha

Reputation: 146249

You didn't tell about ConfideUser class but basically should extend Eloquent

class User extends Eloquent implements UserInterface, RemindableInterface {

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

Same in Book model, ( you didnt tel where Ardent come from and how it's been implemented)

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

You can check relationship and get result using (get users who has book(s))

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

If you query like this

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

In your view you can use

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

Upvotes: 1

Related Questions