Php 如何在雄辩的插入中明确书与作者的关系?
我正在研究如何使用Laravel4插入hasMany条目 Author.php模块Php 如何在雄辩的插入中明确书与作者的关系?,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我正在研究如何使用Laravel4插入hasMany条目 Author.php模块 class Author extends Eloquent //\LaravelBook\Ardent\Ardent { } php模块 class Book extends Eloquent //\LaravelBook\Ardent\Ardent { 我的控制器 $r= new Book(); $r->title = Input::get('
class Author extends Eloquent //\LaravelBook\Ardent\Ardent
{
}
php模块
class Book extends Eloquent //\LaravelBook\Ardent\Ardent
{
我的控制器
$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条记录我在这里插入时没有指向这本书。首先,我认为这是错误的模式,因为可能一个作者可以写多本书 因此,我建议您为此定义多对多(
belongtomany
)关系
无论如何,以下是您问题的解决方案:
// 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
,这样它就有意义了,而且您不会发现自己试图将其视为单个模型(尽管它总是返回集合)
$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 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
}