Laravel 拉雷维尔雄辩的关系总是让我失望
我有三张桌子:Laravel 拉雷维尔雄辩的关系总是让我失望,laravel,eloquent,Laravel,Eloquent,我有三张桌子: 装运 Schema::create('shippings', function (Blueprint $table) { $table->id(); $table->string('name',64); $table->integer('price'); $table->enum('active', ['yes','no'])->default('yes'); $table->enum('ZaPobran
装运
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);
$this->belongsTo(Shipping::class, 'shipping_id');
但是关系“dostawy”总是空的,我不知道为什么。
我尝试将关系更改为hasOne,但更糟糕的是,有人能帮我吗?因为您使用的是
dostawy
,因为relationship eloquent将在orders表中查找dostawy\u id
列。您可以通过如下方式指定希望关系使用的列来轻松覆盖它:
$order = Order::with('products','dostawy')->findOrFail($order_id);
$this->belongsTo(Shipping::class, 'shipping_id');
这将强制关系使用订单
表上的shipping\u id
列,并将其自动链接到shippings
表上的id
列。另外,请注意,如果需要覆盖shippings表上的列名称,可以将其作为第三个参数传入
作为旁注,将关系命名为
shippingDetails
或类似的名称可能是有益的,以使任何开发人员在阅读代码库的过程中都更易于阅读(当然,除非存在导致当前命名的某些业务逻辑) 因为在您的订单
模型中,您使用不同的名称创建了关系方法,所以您需要添加订单的发货id
,id
,如下$this->belongsTo(shipping::class,'shipping\u id',id')
欢迎来到stackoverflow,看看这个问题