php - 当需要一行时,laravel eloquent hasmany 关系返回

标签 php laravel collections eloquent

这方面有很多问题,但我找不到合适的问题。我认为这是非常基本的 Laravel 理解。

我在“属性”和“图像”之间建立了一个简单的关系。对于特定的映射 View ,我需要获取属性数据以及“引导”图像的文件名。因此,根据图像是否被标记为“1”作为数据库中的主要图像,我只需要一个图像结果。

Controller 代码如下所示:

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);
        }

但在 View 中,我能让它工作的唯一方法是使用 foreach 循环,即使我只想要一个结果:

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

这显然是愚蠢的。我想我只是在 View 中遗漏了一些简单的循环,但我可能也误解了如何在 Controller 中解决这个问题。想我现在已经阅读 laravel 文档大约 20 遍了,只是不太了解这个小细节。谢谢。

更新 - 我刚刚又做了一次尝试,并通过在 View 中执行此操作设法摆脱了无意义的 foreach:

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

.. 但这仍然感觉不是很“laravel”.. 仍然希望有任何关于更好的方法的想法。

最佳答案

尝试将 ->get() 更改为 ->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);
        }

关于php - 当需要一行时,laravel eloquent hasmany 关系返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26582589/

相关文章:

php - MySQL插入重复键更新多个值

php - 错误页面中的 Laravel Auth

java - 在Java中增加ArrayList中ArrayList的大小

C# 将 List<ushort> 转换为 List<short>

Java 8 流 - 列表的收集和流映射

php - Paypal API 每两周定期付款

php - 如何重定向用户而不是 Google(和其他抓取工具)?

php - MySQL SELECT(多次)或 SELECT 一次,然后使用数组作为变量

php - XAMPP:Laravel 6.0 的 htdocs 文件夹权限

php - Laravel Eloquent 一对一通过(级别/树)关系