duanmengmiezen8855 2019-06-11 20:48
浏览 102

Laravel - 检查集合是否有关系

I have a form with some checkboxes and when certain checkboxes are checked, I conditionally create a join to an Eloquent model

$collection = Model::with('some_relation')
     ->when(!is_null($request->input('make')), function($query) {
         $query->with('make');
      })
      ->get();

This all works as expected.

What I need to be able to do is check for the existence of that relation in a view. In my view I have a table and need to know if the relation exists and if it does I create a table header for that relation.

I have tried everything I can find and nothing works. I've even tried the following but it returns true even if the relation doesn't exist

$test = $collection->contains(function ($value, $key) {
    return $value['make'];
});

I've also tried count($collection->make); but it says

Property [make] does not exist on this collection instance

All I want it to see if the relationship exists

  • 写回答

1条回答 默认 最新

  • doucan1996 2019-06-12 08:11
    关注

    Found the answer

    $test = $collection->filter->relationLoaded('make')->isEmpty();
    

    Will return true if the relation doesn't exist

    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样