拯救许多关系laravel

时间:2015-11-02 06:05:51

标签: arrays laravel save many-to-many

当我试图挽救许多人的关系时,我有些麻烦 基本上我不知道该怎么做,我只能用同一个表中的简单值来做 我的数据库中有比萨饼,配料和枢轴表ingredient_pizza。 我想为一个披萨保存一些配料,这意味着一系列成分。 当我从比萨饼中读取食材时,我没有问题,但是当我尝试保存到数据库中时,我遇到了问题。

迁移

public function up()
{
    Schema::create('pizzas', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('pizza_name');
        $table->rememberToken();
        $table->timestamps();
    });
}




public function up()
{
    Schema::create('ingredients', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('ingredient_name');
        $table->rememberToken();
        $table->timestamps();
    });
}



public function up()
{
    Schema::create('ingredient_pizza', function(Blueprint $table)
    {
        $table->increments('id');

        $table->integer('pizza_id')->unsigned();
        $table->foreign('pizza_id')->references('id')->on('pizzas');

        $table->integer('ingregient_id')->unsigned();
         $table->foreign('ingregient_id')->references('id')->on('ingregients');

        $table->rememberToken();
        $table->timestamps();
    });
}

比萨的模特

public function ingredients()
{
    return $this->belongsToMany('App\Ingredient');
}

成分的模型

public function Pizza()
{
    return $this->belongsToMany('App\Pizza');
}

我为php1admin设置了pizza1的2种成分,而pizza2没有成分

//it works , 
$pizza1 = Pizza::find(1);
foreach ($pizza1->ingredients as $ingredient){
    echo $ingredient->ingredient_name;   
}


//it works too ,it shows two ingredients and basically i set the same ingredients for pizza2
$pizza2 = Pizza::find(2);
$pizza2->ingredients=$pizza1->ingredients;
foreach ($pizza2->ingredients as $ingredient){
    echo $ingredient->ingredient_name;   
}

但是如果我想保存pizza2的成分我有麻烦 我试过保存在很多方面,但它没有工作

$pizza2->save;
$pizza2->save();
$pizza2->saveMany;
$pizza2->saveMany();
$pizza2->ingredients->save;

如果你能举一个例子,我想用新的成分。 我使用了相同的成分,因为我不知道如何制作新的食材,保存在一个阵列中并同时放入比萨饼

0 个答案:

没有答案
相关问题