【问题标题】:Laravel Eloquent load Data and related Data?Laravel Eloquent 加载数据和相关数据?
【发布时间】:2021-11-25 17:07:51
【问题描述】:

我正在尝试按项目获取所有可用属性及其内容(如果有的话)。 我不知道该怎么形容它。..

一个项目属于一个组。 一个组可以有多个类别。
一个类别可以属于多个组,并且可以具有多个属性。
一个属性有一个类别
一个 PropContent 属于一个项目和属性。

如何按项目获取具有潜在 prop_contents 的类别的所有可用属性?

表格示例:

items groups categories group_categories item_prop_contents category_props
id id id group_id id id
name name name category_id category_prop_id category_id
group_id item_id name
content type (text,bool,int)
class Item extends Model
{
    public function group()
    {
        return $this->belongsTo(Group::class);
    }

    public function contents()
    {
        return $this->hasMany(ItemPropertyContent::class);
    }
}
class Group extends Model
{
    public function categories()
    {
        return $this->hasManyThrough(Category::class, 'group_categories');
    }

    public function items()
    {
        return $this->hasMany(Item::class);
    }
}
class Category extends Model
{
    public function groups()
    {
        return $this->belongsToMany(Group::class);
    }

    public function properties()
    {
        return $this->hasMany(CategoryProperty::class);
    }
}
class CategoryProperty extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function item()
    {
        return $this->belongsTo(Item::class);
    }

    public function contents()
    {
        return $this->hasMany(ItemPropertyContent::class);
    }
}
class ItemPropertyContent extends Model
{
    public function property()
    {
        return $this->belongsTo(CategoryProperty::class);
    }

    public function item()
    {
        return $this->belongsTo(Item::class);
    }
}

我知道它可能没有完全解释,但我不知道如何命名。

感谢您的帮助。谢谢!

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    对于周围的每个人,这是我的解决方案:

            $item->load(['group.categories.properties.content' => function ($query) use ($item) {
                $query->where('item_id', '=', $item->id);
            }]);
    

    【讨论】:

      猜你喜欢
      • 2014-08-30
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 2016-05-25
      • 2015-01-03
      • 2013-06-10
      相关资源
      最近更新 更多