duanjiancong4860 2017-09-25 21:15
浏览 93
已采纳

如何通过匹配关系中的值来获取Laravel模型?

I have a User model with attributes like login, ID, age, etc. Another table is user_data with a residence column, for example.

How can I get all users with a specific residence? I have this:

User model:

public function user_data()
{
    return $this->hasMany('App\Models\UserData');
}

public function FilterUser($request)
{
    if ($request->has('city')) 
    {
        $users = User::with('user_data')->where('residence', 'Warsaw')->get();        
    }

    dd($users);
}

UserData model:

public function user()
{
    return $this->belongsTo('App\User', 'user_id');
}

Now I get this error:

Column not found: 1054 Unknown column 'residence' in 'where clause' (SQL: select * from `users` where `residence` = warsaw and `users`.`deleted_at` is null)

And another question:

If User is my main model, should I connect it with relationships like above? hasMany() or belongsTo()?

  • 写回答

2条回答 默认 最新

  • doujie9252 2017-09-25 21:21
    关注

    Use the whereHas() query builder method:

    $users = User::with('user_data') 
        ->whereHas('user_data', function($query) { 
            $query->where('residence', 'Warsaw'); 
        })
        ->get();
    

    Edit - To use the value from $request you need to import the variable to the closure for whereHas():

        ...
        ->whereHas('user_data', function($query) use ($request) {
            $query->where('residence', $request->city);
        })
        ...
    

    Edit - A query scope may be a better approach. In the User model, add this method:

    function scopeInCity($query, $city)
    {
        return $query->whereHas('user_data', function($q) use ($city) {
            $q->where('residence', $city);
        });
    }
    

    Then you can filter all users by city (outside the model):

    User::inCity($request->city)->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探