laravel 5.5雄辩,搜索关系集合

时间:2018-01-20 06:25:22

标签: php search eloquent laravel-5.5

在我的Prospect表中,我有一些列,其中ID存储为int,表示其他表的项(client_id, consultant_id & house_id),其他列是直接数据,例如street, house_no等。我正在挂钩ID与Eloquent关系,但无法弄清楚我的索引列表搜索这些关系集合。示例client->first_name, client->email or house->name 如果客户 - >名称是John,如何在搜索“john”时显示,如何查看我的搜索? 我有:

Prospect.php模型:

    protected $fillable = ['consultant_id', 'client_id', 'house_id', 'house_spec', 'elevation', 'lot_no', 'house_no', 'street', 'suburb', 'shire', 'estate_name', 'details', 'stage'];

    public function client()
    {
        return $this->belongsTo('App\Client');
    }

    public function consultant()
    {
        // return $this->belongsTo('App\User', 'consultant', 'id');
        return $this->belongsTo(User::class);
    }

    public function house()
    {
      return $this->belongsTo('App\Houses');
    }

和我的ProspectController.php

public function index(Request $request)
    {
        $keyword = $request->get('search');
        $perPage = 25;

        if (!empty($keyword)) {
            $prospects = Prospect::where('client_id', 'LIKE', "%$keyword%")
                ->orWhere('house_id', 'LIKE', "%$keyword%")
                ->orWhere('house_spec', 'LIKE', "%$keyword%")
                ->orWhere('elevation', 'LIKE', "%$keyword%")
                ->orWhere('lot_no', 'LIKE', "%$keyword%")
                ->orWhere('house_no', 'LIKE', "%$keyword%")
                ->orWhere('street', 'LIKE', "%$keyword%")
                ->orWhere('suburb', 'LIKE', "%$keyword%")
                ->orWhere('shire', 'LIKE', "%$keyword%")
                ->orWhere('estate_name', 'LIKE', "%$keyword%")
                ->orWhere('details', 'LIKE', "%$keyword%")
                ->orWhere('details', 'LIKE', "%$keyword%")
                ->paginate($perPage);
        } else {
            $prospects = Prospect::with('client')
            ->with('house')->paginate($perPage);
        }

        return view('prospects.index', compact('prospects'));
    }

1 个答案:

答案 0 :(得分:1)

使用orWhereHas()

$prospects = Prospect::where('client_id', 'LIKE', "%$keyword%")
            ->orWhere('house_id', 'LIKE', "%$keyword%")
            ->orWhere('house_spec', 'LIKE', "%$keyword%")
            ->orWhere('elevation', 'LIKE', "%$keyword%")
            ->orWhere('lot_no', 'LIKE', "%$keyword%")
            ->orWhere('house_no', 'LIKE', "%$keyword%")
            ->orWhere('street', 'LIKE', "%$keyword%")
            ->orWhere('suburb', 'LIKE', "%$keyword%")
            ->orWhere('shire', 'LIKE', "%$keyword%")
            ->orWhere('estate_name', 'LIKE', "%$keyword%")
            ->orWhere('details', 'LIKE', "%$keyword%")
            ->orWhere('details', 'LIKE', "%$keyword%")
            ->orWhereHas('client',function($q) use ($keyword){
                 $q->where('first_name', 'LIKE', "%$keyword%")->orWhere('email', 'LIKE', "%$keyword%");
            })
            ->paginate($perPage);