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