Laravel push()无法正常工作,相关模型未保存

时间:2015-01-27 11:50:55

标签: php class laravel laravel-4

正如官方文件所说:

  

有时您可能希望不仅保存模型,还保存所有模型   它的关系。为此,您可以使用push方法:保存A.   模型和关系$ user-> push();

条款表:

  • term_id
  • 名称
  • 蛞蝓

Term_taxonomy表:

  • term_taxonomy_id
  • term_id
  • 描述

我的期限模型:

public function TermTaxonomy(){
    return $this->hasOne('TermTaxonomy');
}

My TermTaxonomy模型:

public function Term(){
    return $this->belongsTo('Term');
}

my CategoriesController

public  function store(){
    $data = Input::all();
    $category = new Term;
    $category->name = $data['name'];
    $category->slug = $data['slug'];
    $category->TermTaxonomy()->taxonomy = 'category';
    $category->TermTaxonomy()->description  = $data['TermTaxonomy']['description'];
    $category->push();  
}

使用上面的代码,我可以保存名称和slug,但是没有插入分类和描述。我怎么用push()代替save()呢?有可能吗?

谢谢,我是Laravel的新人。

1 个答案:

答案 0 :(得分:0)

据我了解,push()的目的是更新相关模型不插入它们。因为该方法只是遍历所有加载的相关模型并保存它们:

public function push()
{
    if ( ! $this->save()) return false;

    foreach ($this->relations as $models)
    {
        foreach (Collection::make($models) as $model)
        {
            if ( ! $model->push()) return false;
        }
    }

    return true;
}

一个用例就是这样:

$category = Term::find(1);
$category->name = 'foo';
$category->TermTaxonomy->description = 'bar';
$category->push(); // save would only update the name but not the description

我建议您使用Laravel用于inserting related models的方法:

$category = new Term;
$category->name = $data['name'];
$category->slug = $data['slug'];
$taxonomy = new TermTaxonomy();
$taxonomy->taxonomy = 'category';
$taxonomy->description  = $data['TermTaxonomy']['description'];
$category->TermTaxonomy()->save($taxonomy);
$category->save();

或者,如果您的TermTaxonomy模型已配置为进行质量分配,则可以使用create()

$category = new Term;
$category->name = $data['name'];
$category->slug = $data['slug'];
$category->TermTaxonomy()->create([
    'taxonomy' => 'category',
    'description' => $data['TermTaxonomy']['description']
]);
$category->save();

如果确实想要使用push()。这也可行:

$category = new Term;
$category->name = $data['name'];
$category->slug = $data['slug'];
$taxonomy = new TermTaxonomy();
$taxonomy->taxonomy = 'category';
$taxonomy->description  = $data['TermTaxonomy']['description'];
$category->setRelation('TermTaxonomy', $taxonomy);
$category->push();