【问题标题】:Multilingual site with one-to-many relationships in EloquentEloquent 中具有一对多关系的多语言网站
【发布时间】: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 的事情。感谢您一直以来的帮助。

【问题讨论】:

  • 你是怎么查询的?
  • 您的课程似乎定义明确。您如何查询控制器中的模型?

标签: php laravel-4 eloquent


【解决方案1】:

这取决于你到底想要什么。

要获得具有他所有产品语言的产品:

//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;

【讨论】:

  • 这很酷,但我想要反过来。我需要使用它所属的产品加载特定的语言条目。
  • 酷!呵呵,我刚刚更新了我的问题。非常感谢。我会试试这个。至于我要查找的 $id,我假设它是 productlanguage 表中的 id,而不是产品 ID,或者它是如何工作的?
  • 是的,id就是产品语言id
  • 非常感谢您的帮助!您还知道在这种情况下我如何获得特定的语言吗?
  • 只需使用 ->whereLanguage('FR')->get() 代替 find($id)。用您想要搜索的任何内容替换 FR。如果我帮助了你,请点赞。
猜你喜欢
  • 2021-10-09
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
  • 2016-06-04
  • 1970-01-01
  • 2016-08-25
相关资源
最近更新 更多