Laravel eloquent search on fields of related model

后端 未结 2 1951
悲哀的现实
悲哀的现实 2020-12-13 01:10

I have an eloquent models as,

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

Profile : profiles(id, user

相关标签:
2条回答
  • 2020-12-13 01:58

    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 . '%');
                    });
                });
    
            });
    
    0 讨论(0)
  • 2020-12-13 02:03

    That's where whereHas comes in handy:

    $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

    0 讨论(0)
提交回复
热议问题