drd43058 2014-10-27 07:10
浏览 45

当需要一行时,laravel eloquent hasmany relation返回

there are lots of questions in this area, but I can't quite find one that fits. I think it's very basic Laravel understanding.

I have a simple relationship set up between 'properties' and 'images'. For a particular mapping view, I need to get the property data, along with the file name of the 'lead' image. So, I only ever need one image result, according to whether the image is marked '1' as being the lead image in the DB.

Controller code looks like this:

if(Input::get('m') == 'true'){
            //$map_data = Property::all();

            $map_data = Property::with(array('images' => function($query)
            {
                //just grab the lead image to put in the marker popups.
                $query->where('is_lead', 1)->first();

            }))->get();


            return View::make('property_map')->with('data', $map_data);
        }

But in the view, the only way I can get this to work is with a foreach loop, even though I only ever want one result:

@foreach($property->images as $image)
  {{$image->filename}}
@endforeach

Which is obviously daft. I think I'm just missing something simple with that loop in the view, but I may have misunderstood how to address this in the controller too. Think I've read the laravel docs about 20 times now, just can't quite get this little detail. Thanks.

UPDATE - I've just had another go at this, and managed to get rid of the pointless foreach by doing this in the view:

$property->images->first()["filename"]

.. but this still doesn't feel very 'laravel' .. would still appreciate any thoughts on a better way to do this.

  • 写回答

1条回答 默认 最新

  • dqteh7347 2014-10-27 08:25
    关注

    Try changing ->get() to ->first().

    if(Input::get('m') == 'true'){
                //$map_data = Property::all();
    
                $map_data = Property::with(array('images' => function($query)
                {
                    //just grab the lead image to put in the marker popups.
                    $query->where('is_lead', 1)->first();
    
                }))->first();
    
    
                return View::make('property_map')->with('data', $map_data);
            }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示