【问题标题】:How to search into hasMany relationship in laravel如何在laravel中搜索hasMany关系
【发布时间】:2019-02-04 21:58:58
【问题描述】:

我有一个公司和药房的模型

<?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();

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-27
      • 2020-04-29
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多