【发布时间】:2023-04-04 20:36:01
【问题描述】:
我在使用 Eloquent 正确设置和查询关系时遇到问题。我有产品,每个产品都可以根据用户的语言环境有多个名称/描述/价格。现在我的问题是,当我尝试使用这种关系来更新与这些产品有关的数据时,我只能获得产品信息(库存、ID、制造日期等)或语言信息,但不能同时获得两者。我一直在做这件事,浏览了 Eloquent 文档,但那里的例子不是很广泛。这是我的模型:
保存语言特定信息的表格的模型:
class ProductLanguage extends BaseModel {
protected $table = 'products_lang';
protected $fillable = array('title','description','price','language');
public function product(){
return $this->belongsTo('Product');
}
}
产品信息型号:
class Product extends Eloquent {
protected $fillable = array('category_id', 'availability', 'image', 'year', 'stock');
public static $rules = array(
'category_id'=>'required|integer',
'title'=>'required|min:2',
'description'=>'required|min:20',
'price'=>'required|numeric',
'year'=>'required|integer',
'availability'=>'integer',
'image'=>'required|image|mimes:jpeg,jpg,bmp,png,gif'
);
public function category() {
return $this->belongsTo('Category');
}
public function productlanguage(){
return $this->hasMany('ProductLanguage');
}
}
我已经尝试了 L4 文档页面上描述的几乎所有风格来查询这些数据,所以我有两个集合(产品 + 语言),但它根本不起作用。大多数时候我只得到语言数据,有时我得到一个错误,说发现了意外的数据,但无论我做什么,我都无法得到我想要的数据。这里有逻辑错误还是我做错了什么?
更新:这是我目前尝试过的查询。
$product = Product::find($id)->productlanguage()->first();
但是,这感觉很不具体。我也有这个让我得到一切:
$products = Product::with('productlanguage')->get();
棘手的部分是获取产品的语言条目以及匹配的产品信息。我想我会试试这个:
$products = ProductLanguage::with('product')->find($id);
我仍在努力思考整个 Eloquent 的事情。感谢您一直以来的帮助。
【问题讨论】:
-
你是怎么查询的?
-
您的课程似乎定义明确。您如何查询控制器中的模型?