首页 > 解决方案 > Laravel 雄辩的关系总是给我空

问题描述

我有 3 张桌子

Schema::create('shippings', function (Blueprint $table) {
    $table->id();
    $table->string('name',64);
    $table->integer('price');
    $table->enum('active', ['yes','no'])->default('yes');
    $table->enum('ZaPobraniem',['yes','no'])->default('no');
    $table->timestamps();
});

订单

Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->integer('user_id')->unsigned();
    $table->enum('status',['pending', 'paid','sent','done'])->default('pending');
    $table->string('email',64);
    $table->integer('price');
    $table->string('name',64);
    $table->string('secondname',64);
    $table->string('city',64);
    $table->string('street',64);
    $table->text('comment')->nullable();
    $table->string('phonenumber',9);
    $table->string('postalcode',10);
    $table->integer('shipping_id')->unsigned();

    $table->timestamps();
});

class Order extends Model
{
    const PENDING = 'pending';
    const PAID = 'paid';
    const SENT = 'sent';
    const DONE = 'done';

   
    public function products()
    {
        return $this->hasMany(OrderProduct::class);
    }
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function dostawy()
    {
        return $this->belongsTo(Shipping::class);
    }
    
}

订购产品

Schema::create('order_products', function (Blueprint $table) {
    $table->id();
    $table->integer('order_id')->unsigned();
    $table->integer('product_id')->unsigned();
    $table->integer('quantity');
    $table->timestamps();
});

我试图通过这样运行来显示有关特定订单的详细信息:

$order = Order::with('products','dostawy')->findOrFail($order_id);

但是关系'dostawy'总是空的,我不知道为什么。我尝试改变与 hasOne 的关系,但更糟糕的是,有人可以帮助我吗?

标签: laraveleloquent

解决方案


由于您使用dostawy关系 eloquent 将dostawy_id在订单表上查找列。您可以通过指定希望关系使用的列来轻松覆盖它,如下所示:

$this->belongsTo(Shipping::class, 'shipping_id');

这将强制关系使用表shipping_id上的列,orders并自动将其链接到表id上的列shippings。另外,请注意,如果您需要覆盖 shipping 表中列的名称,可以将其作为第三个参数传入。

作为旁注,将关系命名为类似shippingDetails或类似的名称可能是有益的,以使其对任何阅读代码库的开发人员来说更具可读性(当然,除非有一些业务逻辑导致当前命名)!


推荐阅读