如何解决如何获得一对一关系的结果
我正在使用 Laravel 8 制作一个基本的在线订购系统。
在这个项目中,每个订单都是在登录用户的一个用户内提交的。
因此,users
表和 orders
表之间存在一对一关系。
因此,我将这些添加到模型中:
Order.php
:
public function user()
{
return $this->hasOne(User::class);
}
User.php
:
public function order()
{
return $this->belongsTo(Order::class);
}
现在为了得到显示订购者用户名的表的结果,我在控制器上进行了编码:
public function awaiting()
{
$orders = Order::with('user')->where('user_id','!=',NULL)->latest()->paginate(20);
return view('admin.orders.awaiting',compact('orders'));
}
然后在刀锋处:
@foreach($orders as $order)
<tr>
<td>{{ $order->user->name }}</td>
<td>{{ $order->description }}</td>
<td>{{ $order->dimensions }}</td>
<td>{{ $order->color }}</td>
<td>{{ $order->material }}</td>
<td>{{ $order->title }}</td>
<th scope="row">{{ ++$menuCounter }}</th>
</tr>
@endforeach
但这是错误的,因为它在 order_id
表(不存在)中搜索 users
。
那么问题是,如何根据存储在 user_id
表中的 orders
显示已订购的用户的用户名。
更新 #1:
Orders
迁移:
Schema::create('orders',function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('material');
$table->string('color');
$table->string('dimensions');
$table->string('description')->nullable();
$table->tinyInteger('user_id')->unsigned()->nullable();
$table->timestamps();
});
Users
迁移:
public function up()
{
Schema::create('users',function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->tinyInteger('adm')->unsigned()->nullable();
$table->rememberToken();
$table->timestamps();
});
}
解决方法
您可以使用 null
代替检查 whereHas
。尝试更改。
$orders = Order::with('user')->whereHas('user')->latest()->paginate(20);
你们的关系是错的所以
Order.php:
public function user()
{
return $this->belongsTo(User::class);
}
User.php:
public function order()
{
return $this->hasOne(Order::class);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。