我实际上正在尝试在Laravel中创建一个电子商务应用程序,并具有以下数据库布局...
餐桌产品: product_id PK, 材料, 描述, brand_id, category_id,
TABLE PRODUCTS_CHILDREN: ID, sku, 颜色, 价钱, 尺寸, 数量 product_id(从FK到产品表)
现在我是Laravel的初学者,但是我当时正在考虑构建一个电子商务应用程序,只是想在解决问题之前解决这个问题。
我的问题是,在展示产品时,有没有办法同时检索子产品?
我的思考过程是:
产品-> get(product_id,$ product_id)-> getChildren(product_id,product_id);
我知道语法是不正确的,我只是想知道这在Laravel中是否可能解决-通过链接查询(我相信Laravel框架很常见)。
我想我要问的是,显示数据时刀片语法是什么样的?
从我在教程中看到的内容来看,这似乎可行,但我只是想确认一下。谢谢您的帮助!
答案 0 :(得分:2)
是的,一旦您按照documentation建立关系,就可以使用。
例如,在您的示例中,您将有两个模型,一个模型用于products表,另一个模型用于products_children表(我分别称它们为: Product 和 Variant )。
在它们之间,您将具有 1:N 关系(一种产品可以具有多个变体,一个变体属于一个且只有一个产品)。
因此,您可以对关系进行如下建模: 型号:产品
class Product
{
// Other methods/properties...
public function variants()
{
return $this->hasMany(Variant::class);
}
}
型号:变体
class Variant
{
// This is needed, otherwise Laravel would search for a
// table called as the pluralized model name's (eg: variants)
protected $table = 'products_children';
// Other methods/properties...
public function product()
{
return $this->belongsTo(Product::class, 'products_children');
}
}
一旦建立了类似的关系,就可以像示例一样链接方法:
// Assuming $id is the variable holding the product id you want to retrive
$product = Product::find($id);
$variants = $product->variants;
// You can now access the main Product properties, but you can also
// iterate through each Variant entity linked to that product.
根据查询用例,最后一个查询可能不是执行此查询的最佳方法。有时您必须急于加载要查询的所有实体的关系。如果您想更深入地了解此主题,请参阅官方文档。
免责声明:我编写的代码只是一个PoC,未经测试。撰写该文章的目的是为了简要概述如何轻松建立和使用模型之间的关系。