laravel - 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 的关系,但更糟糕的是,有人可以帮助我吗?
解决方案
由于您使用dostawy
关系 eloquent 将dostawy_id
在订单表上查找列。您可以通过指定希望关系使用的列来轻松覆盖它,如下所示:
$this->belongsTo(Shipping::class, 'shipping_id');
这将强制关系使用表shipping_id
上的列,orders
并自动将其链接到表id
上的列shippings
。另外,请注意,如果您需要覆盖 shipping 表中列的名称,可以将其作为第三个参数传入。
作为旁注,将关系命名为类似shippingDetails
或类似的名称可能是有益的,以使其对任何阅读代码库的开发人员来说更具可读性(当然,除非有一些业务逻辑导致当前命名)!
推荐阅读
- node.js - 生产环境集群
- javascript - 搜索不显示产品以及如何显示
- symfony-2.8 - Symfony 中新添加的字段(针对特定实体)未保存
- javascript - res sendFile 不发送任何内容
- python - WebScraping 问题输出为“无”
- node.js - 实现 google Oauth2 (MERN) 时出现 CORS 错误
- pandas - Pandas:从排序的数据框中提取数据
- angular - Firefox/Chrome 在 2000 毫秒内没有被杀死,发送 SIGKILL
- python - 正则表达式匹配 <> 标签内的空格
- c# - 是否可以使用 C# 将 Tempdata 限制为 ASP.NET MVC 中的其他控制器