首页 > 解决方案 > Laravel 从数据库的每一行中选择一张图片

问题描述

我的数据库中有 2 张表,一张有汽车,一张有汽车的图像。是一对多的关系。一辆汽车可以有多个图像,但我想为每辆车选择一张图像。2个表是汽车表:

 Schema::create('cars', function (Blueprint $table) {
        $table->id();
        $table->string('model');
        $table->integer('seats');
        $table->string('fuel');
        $table->integer('year');
        $table->string('color');
        $table->string('gearbox');
        $table->integer('price');
        $table->string('coinType');
        $table->timestamps();
    });

Images table:

    Schema::create('images', function (Blueprint $table) {
                $table->id();
                $table->integer('car_id');
                $table->string('file_name');
                $table->timestamps();
            });

    class Car extends Model
{
    protected $fillable = [
        'model',
        'seats',
        'fuel',
        'year',
        'color',
        'gearbox',
        'price',
        'coinType',
    ];

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


Image model:


    class Image extends Model
{
    protected $fillable = [
        'car_id',
        'file_name'
    ];
    
    public function car()
    {
        return $this->belongsTo(Car::class);
    }

我试图在这样的表之间建立连接:

$images = Image::join('cars', 'images.car_id', '=', 'car.id')
    ->select('images.file_name')
    ->first();

但我只得到该表的第一行。我在这里需要一些帮助,谢谢

标签: databaselaraveleloquent

解决方案


推荐阅读