如何在Eloquent插入中指定书籍和作者关系?

时间:2014-05-29 15:24:39

标签: php laravel laravel-4 eloquent

我正在弄清楚如何使用Laravel 4插入一个hasMany条目

Author.php模块

class Author extends  Eloquent //\LaravelBook\Ardent\Ardent 

{

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模块

class Book extends  Eloquent //\LaravelBook\Ardent\Ardent 

{

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();
}

我的控制器

$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);

我在authors表上得到一条空记录,它指向了我在这里插入的书和其他3条记录而没有指向该书。

1 个答案:

答案 0 :(得分:1)

首先,我认为这是错误的架构,因为可能只有一位作者可以写一本以上的书。

所以我建议您为此定义多对多(belongsToMany)关系。

无论如何,这里是你问题的解决方案:

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

另一个建议:将关系重命名为authors,这样它就是有意义的,你不会试图将它当作一个模型来对待它(虽然它总是返回集合)