douyu7879 2019-05-03 13:50
浏览 300

laravel中是否存在belongsTo关系的位置?

Example

Role -> hasMany -> User

If I want to get all users with a specific role I would normally do something like this:

$role = Role::findOrFail(1);
User::where('role.id', $role->id)->get()

or

User::where('role_id', $role->id)->get()

My question is: Is there any way to achieve that without using role_id or id. I want to just use the $role object. Something like this would be great:

User::where('role', $role)->get();

I know I can use $role->users, but I leaving this out, because I cannot use that if I have multiple belongsTo relations that I want to query.

Example

$model->where('otherModel', $otherModel1)->where('differentModel', $differentModel1)->get();

Background

A solution like this would help a lot, if you want to rename a primary or a foreign key or if your application has keys with counterintuitive names.

  • 写回答

1条回答 默认 最新

  • dounong5373 2019-05-03 15:33
    关注
    User::where('role', $role)->get();
    

    You can't do this or achieve this directly. That is because you are comparing a column (role) to a hole object. What you could do is define Local Scopes.

    I know I can use $role->users, but I leaving this out, because I cannot use that if I have multiple belongsTo relations that I want to query.

    Actually, in this case you are not making use of a belongsTo() relationship but a hasMany() one (the opposite). Again, you could create Local Scopes in order to keep constraining your query to get the users that match your conditions.

    An example using a custom column/value search as you suggested in the last part of your question:

    /** User.php */
    
    public function hasRoleScope($query, $column, $value)
    {
        return $query->where("role.{$column}", '=', $value);
    }
    

    Then you could do:

    /** AnyController.php */
    
    User::has_role('name', 'admin')->get();
    // equivalent to: User::where('role.name', '=', 'admin)->get();
    

    You could keep define another one:

    /** User.php */
    
    public function scopeActive($query, $value)
    {
        return $query->where('active', $value);
    }
    

    Then you could do:

    /** AnyController.php */
    
    User::active(true)->get();
    // equivalent to: User::where('active', true)->get();
    

    The interesting part? You can combine the scopes:

    /** AnyController.php */
    
    User
        ::active(false)
        ->has_role('id', 23)
        ->get();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数