【问题标题】:Getting trouble in writing query laravel在编写查询 laravel 时遇到问题
【发布时间】:2022-01-11 13:41:11
【问题描述】:
Can anyone help me to get the data . 
$ticketList = Ticket::with('appliance', 'brand')->get();
$userAppliances = DB::table('user_appliances')
            ->where('user_id', 5)
            ->pluck('appliance_id')
            ->toArray();

$userBrands = DB::table('user_brands')
            ->where('user_id', 5)
            ->pluck('brand_id')
            ->toArray();

$ticketList = $ticketList->map(function ($ticket) use ($userAppliances) {
                return $ticket->where($ticket->appliance_id,'=', $userAppliances);
            });
            dd($ticketList);

它返回了集合。我想要所有的票,其中ticket->brand_id 和tickt->appliance_id 包括{我从userBrands 和userAppliances 获得的所有id}。我在编写查询时遇到了麻烦

【问题讨论】:

  • 不要使用 map 函数,而是使用 leftJoin 并进行一次查询,这样你的所有条件都与 where 原因一致,你肯定会得到所需的数据

标签: laravel database eloquent mapping eloquent-relationship


【解决方案1】:

试试这个

$userBrands = DB::table ('user_brands')
->where('user_id', 5)
->pluck('appliance_id')
->toArray();

$ticketList = Ticket::with('appliance', 'brand')
   ->where(function($query) use ($userBrands){
     
     $query->whereIn('appliance_id', $userBrands);
})->get();
 

【讨论】:

  • 谢谢 neel 成功了。我还有两个问题。如果我必须:获取ticket.brand_id中不存在userBrand的数据怎么办?而且,有时ticket.brand_id 可能不在表中,在这种情况下它会引发错误,对吗?如果 ticket.brand_id 只存在然后 `$query->whereIn('appliance_id', $userBrands) 否则我应该如何处理,否则忽略这一行? @neel
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多