【问题标题】:Eloquent relationship between vehicle and price车辆与价格之间的雄辩关系
【发布时间】:2021-03-15 10:25:33
【问题描述】:

对雄辩的关系有点困惑。车辆与其价格之间的关系是什么?我需要数据透视表吗?

以下是我的车辆车辆迁移。目标是能够查询与特定价格相关的所有车辆。

    class CreateVehiclesTable extends Migration
    
        {
        
            public function up()
            {
                Schema::create('vehicles', function (Blueprint $table) {
                    $table->id();
        
                    $table->string('title', 256);
                    $table->string('image')->nullable();
                    $table->integer('engineSize')->nullable();
                    $table->integer('numberSeats')->nullable();
                    $table->integer('mileage')->nullable();
                    $table->integer('power')->nullable();
                    $table->integer('doors')->nullable();
                    $table->string('fuel')->nullable();
                    $table->string('gearbox')->nullable();
                    $table->string('color')->nullable();
        
        
                    $table->integer('condition_id');
                    $table->integer('type_id');
                    $table->integer('modell_id');
                    $table->integer('year_id');
                    $table->integer('price');
        
        
                    $table->timestamps();
                });
            }
        
      
            public function down()
            {
                Schema::dropIfExists('vehicles');
            }
        }

【问题讨论】:

  • 你的表结构是什么 - 迁移?没有任何代码是不可能提出建议的。请发布代码。如果您的应用对车辆有单一价格,那么它的 Vehicle hasOne Price 例如
  • 文档非常好。检查一下,以防您的模型尚不存在:laravel.com/docs/8.x/eloquent-relationships#one-to-one
  • 你在这里还需要关系吗?
  • 如果 Price 具有货币、mrp、lrp 等额外属性,则可能需要@brombeer HasOne 关系 - 为数据规范化做出一些努力
  • 通过此迁移,您可以 Vehicle::where('price', $price)->get() 将为您提供与 $price 关联的所有车辆 - 如果这是唯一的要求并且价格没有'没有任何额外的属性,那么您当然不需要单独的价格表

标签: laravel eloquent eloquent-relationship


【解决方案1】:

假设代表车辆记录的模型(您的迁移)是Vehicle

您可以获得与特定价格相关的所有记录 - 例如,$price = 100

$vehiclesAssociatedWithPrice100 = Vehicle::where('price', 100)->get();

你应该阅读 Laravel 文档,它们真的很容易解释

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 2018-07-24
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 2017-10-12
    • 1970-01-01
    相关资源
    最近更新 更多