database - 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();
但我只得到该表的第一行。我在这里需要一些帮助,谢谢
解决方案
推荐阅读
- asynchronous - Vue.js v-show 在 axios 之后不起作用
- database - Laravel(不仅如此)多对多关系 Belongs-To-All
- html - 固定 div 高度:移动设备上滚动未填满屏幕时为 100%
- twilio - 是否可以检测到谁在使用 Twilio Video JS SDK 说话?
- svn - SVN 最佳实践——开发人员的“私有”存储库?
- python - python 中的 Azure 计费 API
- windows-10 - windows 10 家庭基本功能错误
- database - 签名板 将签名存储在数据库中
- c# - T-SQL:合并或更新子表
- c# - Linq通用GroupBy日期和其他字段同时