首页 > 解决方案 > 是否可以通过这种方式从相关表中获取值名称

问题描述

好的,所以我需要以这种方式从表中获取数据,但我也想获取 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 所以某种加入会起作用在这种情况下

标签: phplaraveleloquent

解决方案


好的基于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来抛出一个实例。


推荐阅读