Skip to content
Advertisement

How to specify Books and Authors relationship in Eloquent insertion?

I was figuring out how to insert a hasMany entry using Laravel 4

Author.php module

class Author extends EloquentLaravelBookArdentArdent 
{

    
    public static $rules = array(

    'title'             =>  'required',
    'last_name'         =>  'required',
    'first_name'        =>  'required',

    
    );


    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'authors';

      public function abstraction()
    {
        return $this->belongsTo('Book','book_id');
    }
    
    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getRegId()
    {
        return $this->getKey();
    }
}

Book.php Module

class Book extends EloquentLaravelBookArdentArdent 
{

    
    public static $rules = array(

    'title'             =>  'required',
    'authors'           =>  'required',

    );


    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'abstracts';

    public function author()
    {
        return $this->hasMany('Author');
    }
    
    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getRegId()
    {
        return $this->getKey();
    }

}

My controller

$r = new Book();

$r->title = Input::get('title');
$r->authors = Input::get('authors');
$r->affiliation = Input::get('affiliation');
$r->keywords = Input::get('keywords');
$r->summary = Input::get('summary');

$r->save();
$authors = new Author();
$authors_array = array(
    array('name' => 'Arun1', 'affiliation' => 'aff_arun'),
    array('name' => 'Arun2', 'affiliation' => 'aff_arun'),
    array('name' => 'Arun3', 'affiliation' => 'aff_arun3'),
    array('name' => 'Arun4', 'affiliation' => 'aff_arun'),
);

$authors->book()->associate($r);

$authors->save($authors_array);

I’m getting one null record on authors table which pointed to the book and other 3 record that I inserted here without any pointing to the book.

Advertisement

Answer

First off I believe this is wrong schema, since probably one author could write more than a single book.

So I suggest you define many-to-many (belongsToMany) relation for this instead.

Anyway here is solution to your problem:

// I wonder why you call the book $r ?
$r = new Book;
...
$r->save();

$authors_array = array(...);

foreach ($authors_array as $author)
{
   $r->author()->save(new Author($author)); 
   // you need $fillable/$guarded on Author model or it will throw MassAssignementException
}

Another suggestion: rename the relation to authors so it is meaningful and you won’t catch yourself trying to treat it like a single model (while it always returns the Collection)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement