检索 laravel 中的第一个外键值

retrieve forign key first value in laravel

我有三个 tables 产品、类别和图像。类别和图像 table 与产品 table 有关系。当我使用$all_product = Product::with('category','image')->get();产品信息类别信息和图像信息显示成功我想要的是问题:如何检索图像数组的第一个值?

"all_objects": [
    {
        "id": 1,
        "name": "samsung",
        "price": "2000",
        "category_id": 1,
        "created_at": "2020-02-17 13:27:24",
        "updated_at": "2020-02-17 13:27:24",
        "category": {
            "id": 1,
            "category_name": "android",
            "created_at": "2020-02-17 13:26:42",
            "updated_at": "2020-02-17 13:26:42"
        },
        "image": [
            {
                "id": 1,
                "image_name": "image_787.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 2,
                "image_name": "image_539.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 3,
                "image_name": "image_606.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 4,
                "image_name": "image_102.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:26",
                "updated_at": "2020-02-17 13:27:26"
            }
        ]
    },

试试这个:

$all_product = App\Product::with(['category','image' => function ($query) {
    $query->first();
}])->get();

Constraining Eager Loads

get() 方法 returns Illuminate\Database\Eloquent\Collection 的一个实例,因此您可以在 Laravel collections.

上使用所有可用的方法

获取您的第一张图片:

$all_product = Product::with('category','image')->get();

foreach ($all_product as $product) {
    $first_image = optional($product->image)->first();

    // do whatever you want with the $first_image
}

optional() 方法用于没有图像的案例产品(即 $product->images 为空)。