Laravel 8: 如何向所有管理员用户发送电子邮件通知

Laravel 8: How to send email notification to all admin users

我在 User 模型和 Order 模型之间有一个 一对多 关系:

User.php:

public function order()
    {
        return $this->hasMany(Order::class);
    }

Order.php:

public function user()
    {
        return $this->belongsTo(User::class);
    }

现在我需要从订单访问用户实例:

$order = Order::where('id', $id)->update(['status' => 'verified', 'price' => $data['price']]);
$user = $order->user;
dd($user);

但是这样,我得到这个错误:

Trying to get property 'user' of non-object

那么如何解决这个问题并正确访问用户实例呢?

这是 orders table 的迁移:

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();
        });

更新方法不会 return 订单详细信息,因为更新 return truefalse。所以改成

$order = Order::find($id);
$order->status='verified';
$order->price=$data['price'];
$order->save();
$user = $order->user;

update 方法将数组作为参数 update(array $values) 和 return int

为什么不在迁移中添加关系作为 foreignID?

 $table->foreignID('user_id')->constrained();