php - 是否可以通过这种方式从相关表中获取值名称
问题描述
好的,所以我需要以这种方式从表中获取数据,但我也想获取 Vehicle Maker 名称
我尝试使用 join 或只是做auth()->user()->vehicles->VehicleMaker
,但它不起作用
台车迁移
Schema::create('vehicles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id');
$table->bigInteger('category_id');
$table->bigInteger('vehicle_maker_id');
$table->string('name');
$table->double('price', 8 , 2);
$table->year('manufacture_year');
$table->bigInteger('mileage');
$table->string('vehicle_image');
$table->boolean('admin_verification')->nullable();
$table->timestamps();
});
车辆制造商的迁移
Schema::create('vehicle_makers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
控制器
public function show(){
$vehicles = auth()->user()->vehicles; -- what shoul i add here
return view('/home', [
'vehicles' => $vehicles
]);
}
编辑
我忘了提到我已经建立了关系,当我尝试做这样的事情时他们在工匠修补匠中工作:
Vehicles->find(1)->VehicleMaker
我想要做的是
auth()->user()->vehicles
用 vahicle_maker 名称而不是 id 获得车辆 teble 所以某种加入会起作用在这种情况下
解决方案
好的基于Laravel 模型关系。
您首先需要创建一个migration
.
车辆迁移
Schema::create('vehicles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('vehicle_maker_id');
$table->string('name');
$table->double('price', 8 , 2);
$table->year('manufacture_year');
$table->bigInteger('mileage');
$table->string('vehicle_image');
$table->boolean('admin_verification')->nullable();
$table->timestamps();
});
我曾经
unisignedBigInteger
确定它是外键,或者你也可以使用index()
.
在您的模型中,您应该放置您将使用的关系。在您的情况下,我假设您使用的是一对多关系。这样您的用户模型应该如下所示:
用户模型
...
public function vehicles() {
return $this->hasMany(Vehicle::class);
}
这样你就可以使用约定了
auth()->user()->vehicles;
。注意:
auth()->user()->vehicles;
返回 aarray of object
你可以将它循环到foreach
.
车型
public function user() {
return $this->belongsTo(User::class);
}
当你的模型中有这个时,你可以用两种方式使用它。
在您的控制器中,您可以调用这 2 个之间的关系。
控制器
$vehicles = auth()->user()->vehicles;
dd($vehicles);
信息
您也可以参考本教程。
编辑
控制器
$vehicles = auth()->user()->vehicles();
foreach($vehicles as $vehicle) {
dd($vehicle->VehicleMaker);
}
注意:
$vehicles
正在返回一个对象数组。所以你可以循环它foreach loop
来抛出一个实例。
推荐阅读
- c - C 中的 Valgrind 错误:使用结构、链表和指针。大小为 1 的无效读取和进程以信号 11 的默认操作终止
- spring-boot - 在 SpringBootTest 中禁用使用 spring.config.import 激活的配置服务客户端
- linux - 检查 .o 文件中的调试符号
- python - 在python中实现函数分数微分方程的欧拉方法
- python - 从熊猫数据框中同一列的可用数据中转换缺失的列数据?
- php - php - 动态标题
- arrays - 将指针与数组一起使用
- php - 如何使用 php 验证学校电子邮件域
- c# - C#简单链表中的“this”
- java - 如何将屏幕截图和自定义消息嵌入到使用 cucumber 生成的 Masterthought 报告中?