嗨,我是 laravel 的新手( Eloquent )。我正在尝试使用 Eloquent ORM 建立通过(级别/树)关系的一对一关系。我有 product_category
表,其中包含 id
和 parent_id
。
这是我的product_category
表
|-----|--------|-----------|
| id | name | parent_id |
|-----|--------|-----------|
| 1 | book | 0 |
| 2 |notebook| 1 |
这是我的产品
表
|----|----------------|-------------|
| id | name | category_id |
|----|----------------|-------------|
| 1 | super notebook | 2 |
我希望能够单独从产品的 subcategory_id 信息中提取父类别信息。这可能吗?
当使用 SQL 时,这是查询(假设 category_id
为 2)
SELECT * FROM `product_category` WHERE `id` = (SELECT `parent_id` FROM `product_category` WHERE `id` = '2' )
更新:
这是我目前的实现
<?php
class Product extends Eloquent {
public function subcategory()
{
return $this->hasOne('ProductCategory');
}
public function category()
{
// This should get the parent info of the subcategory
return ProductCategory::find($this->subcategory->parent_id);
}
}
最佳答案
基本的 1-2-1 关系是这样完成的:
产品型号
class Product extends Eloquent {
public function category()
{
return $this->hasOne('Category');
}
}
类别模型
class Category extends Eloquent {
public function product()
{
return $this->belongsTo('Product');
}
}
现在您可以像这样查询数据:
Product::find(1)->category;
生成的 SQL:
从 id = 1 的产品中选择 *
从 product_id = 1 的类别中选择 *
基本上你应该重命名你的列以匹配 laravels 默认值,否则设置键 $this->hasOne('Category', 'foreign_key');
关于php - Laravel Eloquent 一对一通过(级别/树)关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20798456/