首页 文章

如何在laravel中搜索hasMany关系

提问于
浏览
0

我有公司和药房的模型

<?php 
// Company.php

public function dispensary() 
{
   return $this->hasMany(Dispensary::class);
}

// Dispensary.php
public function company()
{
    return $this->belongsTo(Company::class);
}

我想要的是首先得到用户所属公司的药房 .

$auth = \Auth::user();
$userCompany = $auth->company()->get();

$dispensaries = Company::find($userCompany->first()->id)->dispensary;

如何构建查询,用户可以在其中搜索用户所属的药房列表 .

我曾尝试使用whereHas,但它正在从公司而不是药房进行搜索

Company::find($userCompany->first()->id)
    ->whereHas('dispensary', function ($query) use ($name) {
       $query->where('name', 'like', "%{$name}%");
})->get();

1 回答

  • 0

    好吧,我终于通过使用where子句使它工作了

    $company = Company::find($id)->dispensary()
            ->where('name', 'like', "%{$name}%")
            ->where('contact_email', 'like', "%{$email}%")
            ->get();
    

相关问题