Laravel 雄辩搜索领域相关模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28913014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:54:50  来源:igfitidea点击:

Laravel eloquent search on fields of related model

laraveleloquent

提问by Dipendra Gurung

I have an eloquent models as,

我有一个雄辩的模型,

User: users(id, username, password, email, status)

用户用户(ID,用户名,密码,电子邮件,状态)

Profile: profiles(id, user_id, first_name, last_name, gender, dob)

个人资料个人资料(id、user_id、first_name、last_name、gender、dob)

In the controller logic, I am eagerly loading the Profile model.

在控制器逻辑中,我急切地加载 Profile 模型。

I can do this,

我可以做这个,

$user = User::with('Profile')->get();

or

或者

$user = User::with('Profile')->where('status', '1')->get();

but how to do something like,

但如何做类似的事情,

$user = User::with('Profile')->where('status', '1')->where('gender', 'Male')->get();

回答by lukasgeiter

That's where whereHascomes in handy:

这就是whereHas派上用场的地方:

$user = User::with('Profile')->where('status', 1)->whereHas('Profile', function($q){
    $q->where('gender', 'Male');
})->get();

Basically it adds the condition that the user needs to have a profile with gender = Male

基本上它增加了用户需要有一个配置文件的条件 gender = Male

回答by Marosdee Uma

If you want to search multiple columns in relation model.

如果要搜索关系模型中的多列。

        $searchText = 'test text';
        Product::with('owner')->where(function($query) use ($searchText)
        {
            $query->where('product_name', 'LIKE', '%' . $searchText . '%');

            $columns = ['product_code', 'place_location', 'remark'];

            foreach ($columns as $column ) {
                $query->orWhere($column, 'LIKE', '%' . $searchText . '%');
            }

            $query->orWhereHas('owner', function($q) use ($searchText) {
                $q->where(function($q) use ($searchText) {
                    $q->where('name', 'LIKE', '%' . $searchText . '%');
                    $q->orWhere('company_name', 'LIKE', '%' . $searchText . '%');
                });
            });

        });