[英]Multilingual site with one-to-many relationships in Eloquent
我有使用Eloquent正確建立和查詢關系的問題。 我有產品,並且每個產品可以根據用戶的區域設置具有多個名稱/說明/價格。 現在我的問題是,當我嘗試使用這種關系來更新與這些產品有關的數據時,我只能獲得產品信息(庫存,編號,生產日期等)或語言信息,而不能同時獲得兩者。 我一直在研究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);
我仍在努力圍繞這整個雄辯的事情。 感謝您一直以來的幫助。
這取決於您到底想要什么。
要獲得具有所有產品語言的產品:
//This retrieves one product by id, and loads simultaneously the productlanguages
$product=Product::with('productlanguage')->find($id);
//This retrieves only the productlanguages as an Array
$productlanguages=$product->productlanguage;
或相反:
$productLanguage=ProductLanguage::with('product')->find($id);
$product=$productLanguage->product;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.