我有一个模型的关系方法, 它的条件是基于模型本身的属性.
// ProductController.php
public function show($id, Request $request) {
$product = Product::find($id);
if ($request->exists('optionValues') {
$product->load('optionValues');
}
}
// Product.php
public function optionValues()
{
/// here $this->stock_status_id is null. actually all attributes array is empty.
if ($this->stock_status_id == Stock::CUSTOM_ORDER) {
return $this->hasMany(ProductOptionValue::class, 'product_id', 'product_id')
->where('status', 1);
}
return $this->hasMany(ProductOptionValue::class, 'product_id', 'product_id')
->where('price', '>', 0)
->where('quantity', '>', '0')
->where('status', 1);
}
但是当Laravel加载关系时, 似乎所有的属性都是空的. $this->stock_status_id
对于当前模型是空的,我无法检查条件。
有什么办法可以解决这个问题吗?
经过2个小时的调试, 我发现Laravel在使用关系方法时有不同的加载方式. $model->load('relationName')
方法,而不是通过 $model->relationName
当使用 ->load('relationName')
方法,但模型的实例没有属性,即使在调用 $model->load()
.
但当使用 $model->relationName
在一个模型实例上,当试图加载关系时,该实例有所有的属性存在。
所以,我修改了这行代码
$product->load('optionValues');
以此。
$product->optionValues;
和条件检查在 optionValues()
方法,按预期工作。