Laravel雄辩地询问多种关系

时间:2017-05-21 08:32:10

标签: php mysql laravel eloquent

我有四个表departmentsusersitemsitems_inventories

这种关系是这样的:

user已分配departmentitem已分配departmentitem_inventories有很多项目。

结构:

users
->id
->name
->password
->access_type (department_id)

departments
->id
->name

items
->id
->name
->department_id

items_inventories
->id
->item_id
->qty

我的模特:

class Item extends Model
{
    public function department()
    {
        return $this->hasOne('App\Http\Models\Department', "id", "department_id");
    }
}


class ItemsInventory extends Model
{
    public function item()
    {
        return $this->hasOne('App\Http\Models\Item', "id", "item_id");
    }
}

在我的items_inventories中如何查询属于特定部门的所有项目?由于items已经与departments建立了关系,我如何查询:选择items_inventories中item department_id等于3的所有项目?

我的目标是,我有一位用户已登录,当我的页面加载时,我可以通过access_type(department_id)访问指定的部门给我/她,我只想列出{中的项目{1}}分配给他/她的部门。我已经检查过:items_inventories但似乎无法找到符合我要求的内容。感谢

1 个答案:

答案 0 :(得分:0)

你们的关系有点令人困惑。表格结构表明items属于departmentsitem inventories属于items。我根据您的桌面结构建立了关系,以及如何实现您想要的结果。您可能希望再次检查您的关系,以验证您希望它如何平移。至于目前的关系,我的模型应该给你一个想法。

class User extends Model
{
    public function department()
    {
        return $this->belongsTo('App\Http\Models\Department', 'access_type');
    }
}

class Department extends Model
{
    public function items()
    {
        return $this->hasMany('App\Http\Models\Item');
    }

    public function itemInventory()
    {
        return $this->hasManyThrough('App\Http\Models\ItemsInventory', 'App\Http\Models\Item');
    }
}

class Item extends Model
{
    public function department()
    {
        return $this->belongsTo('App\Http\Models\Department');
    }

    public function itemInventory()
    {
        return $this->hasMany('App\Http\Models\ItemsInventory');
    }
}

class ItemsInventory extends Model
{
    public function item()
    {
        return $this->belongsTo('App\Http\Models\Item');
    }
}

控制器逻辑

$department_id = 3;

$itemInventory = ItemsInventory::whereHas('item', function ($query) use ($department_id) {
    $query->where('department_id', $department_id);
})->get();

// With user:department relation and department:iteminventory 'hasManyThrough' relation.

$itemInventory = $user->department()->itemInventory;