【问题标题】:Where query in both relationships Laravel 7在两种关系中查询 Laravel 7
【发布时间】:2021-03-21 06:03:24
【问题描述】:

我怎样才能得到 所有用户 哪些名称以给定的字符串开头,以及他们的 cityprofile 关系在哪里等于 伦敦?

$users = User::where('name', 'LIKE', "{$searchingName}%")->with('profile')->get();

【问题讨论】:

  • 使用whereHas()函数:laravel.com/docs/8.x/…whereHas('profile', function($subQuery){ return $subQuery->where('city', 'London'); })(假设 city 是列而不是另一个关系。)

标签: laravel eloquent relationship


【解决方案1】:

您可能会发现whereHas 非常有用:

use Illuminate\Database\Eloquent\Builder;

// Retrieve profiles where the city is like 'London'.
$users = User::where('name', 'LIKE', "{$searchingName}%")
              ->whereHas('profile', function (Builder $query) {
                   $query->where('city', 'like', 'London');
              })->get();

【讨论】:

  • 谢谢。我尝试了完全相同的事情。但出现意外错误。现在我看到我失踪了-> 使用 Illuminate\Database\Eloquent\Builder;它有效。
猜你喜欢
  • 2019-01-10
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多