Laravel Eloquent 从关系中选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15942195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:41:45  来源:igfitidea点击:

Laravel Eloquent select from relationship

phplaravelrelationshiplaravel-4eloquent

提问by RGweb

I've been trying to get the hang of Laravel. I'm using Laravel 4. Right now I have two tables, a 'Products' table and a 'Images' table. A product can have many images and an image belongs to a product.

我一直在努力掌握 Laravel 的窍门。我正在使用 Laravel 4。现在我有两个表,一个“产品”表和一个“图像”表。一个产品可以有多个图片,一个图片属于一个产品。

So I have two models:

所以我有两个模型:

class Product extends Eloquent {

    public function images()
    {
        return $this->hasMany('Image');
    }

}

class Image extends Eloquent {

    protected $table = 'product_images';

    public function product()
    {
        return $this->belongsTo('Product');
    }

}

Now I'm building the 'index' page of a resource, so I do Product::all() in the controller and send this to the view.

现在我正在构建资源的“索引”页面,因此我在控制器中执行 Product::all() 并将其发送到视图。

In the view I do a foreach and loop over all products. But now I want to get an image to show with the product. But I can't seem to figure out how to get, for instance, the first image.

在视图中,我执行 foreach 并遍历所有产品。但现在我想要一张图片来展示产品。但我似乎无法弄清楚如何获得,例如,第一张图片。

When I do $product->imagesI get an object of all images related to the product.

当我这样做时,$product->images我会得到与产品相关的所有图像的对象。

When I do $product->images->urlI get an error (Undefined property 'url')

当我这样做时,$product->images->url我收到一个错误(未定义的属性“url”)

I've tried $product->images->first()->urlthis also gives an error (Trying to get property of non-object)

我试过$product->images->first()->url这也给出了一个错误(试图获取非对象的属性)

What am I doing wrong?

我究竟做错了什么?

采纳答案by Dwight

The imagesproperty is an array-like property that you can loop through.

images属性是一个类似数组的属性,您可以循环遍历。

foreach ($product->images as $image) {
    echo $image->url;
}

Alternatively, if you only wanted the first, you can access the index.

或者,如果您只想要第一个,则可以访问索引。

$product->images[0]->url;

回答by Max Ehsan

Have you tried eager-loading?

你试过急切加载吗?

foreach (Product::with('images')->get() as $product)
{
    echo $product->images->first()->url;
}

回答by Marko Aleksi?

You can try using the following PHP function.

您可以尝试使用以下 PHP 函数。

$first_image = array_shift($product->images);

Then, $first_image will be one image object, and accessing the URL of the image should be easy: $first_image->ulr

然后, $first_image 将是一个图像对象,并且访问图像的 URL 应该很容易: $first_image->ulr

Note: Haven't tested it, but should work. Let us know.

注意:还没有测试过,但应该可以工作。让我们知道。