我正在研究Laravel中的批量分配,并试图为一个模型及其相关模型批量分配数据。
我的模型:
class News extends Eloquent {
protected $table = 'news';
protected $fillable = array(
'title', 'slug', 'author', 'img', 'content',
);
public function content() {
return $this->morphMany('Content', 'morphable')->orderBy('section');
}
}
class Content extends Eloquent {
protected $table = 'contents';
protected $fillable = array(
'rawText', 'section',
);
public function morphable() {
return $this->morphMany();
}
}
我的输入
我有一个Input:all()
,看起来像这样,来自于表单:
array(6) {
["_token"]=>
string(40) "irrelevant"
["title"]=>
string(11) "Happy Title"
["author"]=>
string(9) "Mr. Happy"
["slug"]=>
string(11) "happy-title"
["img"]=>
string(9) "happy.png"
["content"]=>
array(1) {
[0]=>
array(2) {
["section"]=>
string(4) "body"
["rawText"]=>
string(27) "# I'm happy! ## So happy"
}}}
现在我该怎么做才能将数据实际保存为两个新的数据库行?(一个在新闻中,一个在内容中)
我以为现在会很简单:
$news = News::create(Input::all());
$news->push();
但我显然错过了什么。
我得到错误:preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
批量分配对相关模型根本不起作用吗?
或者它工作得很好,但不适用于morphMany关系?
我是否误解了$model->push()
或$model::create
?
提前谢谢。
与SO问题一样,写作和格式化给了我一些思考的时间。。
$input = Input::all();
$contents = Input::get('content');
unset($input['content']);
$news = News::create($input);
foreach ($contents as $c) {
$content = Content::create($c);
$news->content()->save($content);
}
$news->save();
工作!但感觉有点生气。还有更多…吗。。大规模分配相关模型的"冗长"方式?
编辑:这可能是通常正确的操作过程-批量分配不会处理关系,但至少我可以单独批量分配每个模型。
我只需要稍微处理一下输入,一旦将验证添加到等式中,我可能无论如何都必须这样做。
第2版:成功地将相关模型逻辑移动到该模型中,并保持简单,例如:
$input = Input::all();
unset($input['content']);
$news = News::create($input);
$news = Content::updateAll($news, true);
$news->save();
用于创建,以及:
$input = Input::all();
unset($input['content']);
$news = News::find($id)->fill($input);
$news = Content::updateAll($news, false);
$news->save();
用于更新。
updateAll()
方法,适用于任何感兴趣的人:
public static function updateAll($model, $create = false) {
$contents = Input::get('content');
foreach ($contents as $k => $c) {
// Save against parent model
if ($create) {
$content = Content::create($c);
} else {
$content = Content::find($k)->fill($c);
}
$model->content()->save($content);
}
return $model;
}
现在我感觉我在用全力!