我一直在试图弄清楚如何更新我的hasMany关系模型。我可以轻松地创建新的关系,但是当我尝试更新我的关系模型时它不起作用? laravel push()方法是否仍然有效?有人可以帮忙吗?例如,我想更新与Controller中的Products表相关的分类表。我在下面有一段代码片段
Product.php
class Product extends Model
{
protected $fillable = [
'product_category', 'product_subcategory', 'product_name',
'product_price', 'product_id', 'product_description', 'product_image'
];
protected $primaryKey = 'product_id';
public $incrementing = false;
public function addTaxonomiesToProduct()
{
return $this->hasOne('App\Taxonomies', 'product_id', 'product_id');
}
}
Taxonomies.php
class Taxonomies extends Model
{
protected $fillable = ['product_category', 'product_subcategory'];
protected $primaryKey = 'product_id'; // or null
public $incrementing = false;
public function product()
{
return $this->belongsTo(Product::class);
}
}
EditProductController.php
class EditProductController extends Controller
{
public function update(Request $request, Product $product)
{
$product_size = array();
foreach ($request->product_size as $key => $value)
{
array_push($product_size,$value);
}
$product->update([
'product_name' => $request->product_name,
'product_price' => $request->product_price,
'product_description' => $request->product_description,
'product_size' => serialize($product_size),
'product_image' => $product_image_path,
]);
/**
* Go the products table,
* Get the product based off its product_id,
* and then update this products taxonomy
**/
$taxonomies = Product::find($product->product_id);
$taxonomies->addTaxonomiesToProduct->product_subcategory = "Mens Shoes";
$taxonomies->push();
}
}
****更新已发布解决**** 通过在我的Products表中将hasMany()更改为hasOne(),我的分类表已正确更新。
答案 0 :(得分:0)
我认为你并不完全理解Laravel Eloquent关系的运作方式。首先,您需要在两个模型中定义关系。您的分类模型有此,但您的产品模型应具有:
public function taxonomies()
{
return $this->hasMany('App\Taxonomies', 'product_id', 'product_id');
}
然后要更新产品的分类,你会有类似......呃,我不确定你在这里想要达到的目标,特别是对你的方式链接product_subcategory
,所以我不能正确地说,但确实看到the documentation