【问题标题】:Laravel 8: How to send email notification to all admin usersLaravel 8:如何向所有管理员用户发送电子邮件通知
【发布时间】:2021-06-23 18:51:42
【问题描述】:

我在 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表的迁移:

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

【问题讨论】:

  • 用户表中的id字段和订单表中的user_id字段必须具有相同的数据类型,如果您在用户表中使用了$table->id(),则使用$table->unsignedBigInteger(' user_id')->nullable() 顺序表迁移文件

标签: php laravel eloquent one-to-many laravel-8


【解决方案1】:

更新方法不会返回订单详细信息,因为更新返回true 或false。所以改成

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

update 方法将数组作为参数 update(array $values) 并返回 int

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-23
      • 2021-11-05
      • 2019-12-05
      • 2012-10-11
      • 2013-10-28
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      相关资源
      最近更新 更多