这样可以从相关表中获取值名称

问题描述 投票:0回答:2

好,所以我需要以这种方式从表中获取数据,但我想获取车辆制造商名称也]

我尝试使用join或只是做uth()-> user()->车辆-> VehicleMaker,但它不起作用

//Migration
Example of Table Vehicle
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();
});
Example of Table Vehicle

Schema::create('vehicle_makers', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});
//Controller
public function show(){

    $vehicles = auth()->user()->vehicles; -- what shoul i add here

    return view('/home', [
       'vehicles' => $vehicles
    ]);
}
php laravel
2个回答
0
投票

好的,基于Laravel Model Relationship

您首先需要创建一个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()

在模型中,您应该放置将使用的关系船。在您的情况下,我假设您正在使用One To Many Relationship。这样您的用户模型应如下所示:

用户模型

...
public function vehicles() {
  return $this->hasMany(Vehicle::class);
}

以便您可以使用约定auth()->user()->vehicles;

注意:auth()->user()->vehicles;返回一个array of object,您可以在foreach中循环它。

车辆型号

public function user() {
  return $this->belongsTo(User::class);
}

在您的模型中拥有此功能时,可以使用2种方式。

在您的控制器中,您可以调用这2个的关系。

Controller

$vehicles = auth()->user()->vehicles;

dd($vehicles);

INFO

您也可以参考此tutorial


0
投票

使用者和车辆之间应该有一种关系,而车辆和车辆制造商之间应该有另一种关系。如果您已经使用迁移创建了模型(Vehicle,VehicleMaker),则可以执行以下操作

//add this to your User model.

public function vehicle(){
    return this->belongsTo(App\Vehicle);
}

// add this to your Vehicle model

public function user(){
    return this->hasMany(App\Vehicle); // implying that a user can have many vehicles
}

//add this to your vehicleMaker model

public function vehicle(){
    return this->belongsTo(App\Vehicle);
}

完成后,您可以使用Laravel的延迟加载来获取关系。您可以执行类似的操作

$vehicles = auth()->user()->vehicle
   return view('/home', [
   'vehicles' => $vehicles
]);
© www.soinside.com 2019 - 2024. All rights reserved.