【问题标题】:Laravel related model attributes are empty?Laravel 相关模型属性为空?
【发布时间】:2019-06-19 20:50:10
【问题描述】:

我试图让用户能够看到他的订单。我已经创建了关系,但是当我(dd)函数的结果时,相关的模型属性为空。

我不知道怎么了。

这是我的买家功能

//买家订单

 public function myOrders()
 { 
 $user = User::find(auth()->user()->id); 
 $user = $user->products();
 dd($user);// related model attributes shows empty

 return view('myOrders')->with(compact('user'));

 }

这是我的用户

 public function products()
 {
  return $this->hasMany(Products_model::class);
 }

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

public function allOrdersBuyerSeller() 
{ 
return $this->hasMany(OrderProduct::class); 
}

products_model

 public function orders() 
 {
return $this->belongsToMany('App\Order', 'order_product');
 }

 public function user() 
 {
return $this->belongsTo('App\User');
 }

用户迁移

  */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
  }

产品迁移

  public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('pro_name');
        $table->integer('pro_price');
        $table->text('pro_info');
        $table->integer('stock');
        $table->integer('category_id');
        $table->string('image')->nullable();
        $table->timestamps();

        $table->bigInteger('seller_id')->unsigned()->index();
        $table->foreign('seller_id')->references('id')->on('users')->onDelete('cascade');
    });
   }

我想查看表格的属性,例如价格、名称、信息、img 等。

【问题讨论】:

  • 旁注,User::find(auth()->user()->id) 是多余的; auth()->user() 很可能包含相同的内容,只是一个额外的数据库查询。 Products_model 也应该是 Product;与命名一致。这也可能导致你们的关系出现问题。您能否将您的用户和产品迁移包括在内?
  • 我应该使用什么? @蒂姆刘易斯
  • auth()->user()->products,或auth()->user()->products()->get()
  • 我已经更新了产品和用户迁移的问题@TimLewis
  • 你的代码到处都是......为什么你的myOrders()函数返回Products?

标签: php database laravel eloquent


【解决方案1】:

除了关于您的代码的 cmets,您没有看到 products 查询结果的原因是您没有将闭包传递给查询。

$user = $user->products();

目前,$user 是一个 QueryBuilder 实例。在您使用closure 之前,您将无法看到这些行。修改你的代码如下:

$products = $user->products;
// OR
$products = $user->products()->get();

如果您省略(),它将使用products()->get() 加载关系,除非已经加载。

编辑:您可能需要在关系中包含外键,因为模型名称不匹配:

用户.php

public function products(){
  return $this->hasMany(Product_model::class, "seller_id", "id");
}

最好查看关系文档的内容; https://laravel.com/docs/5.8/eloquent-relationships。在命名、查询等方面存在很多不正确的做法。

【讨论】:

  • 它只是显示像这样的空数组Collection {#293 ▼ #items: [] }
猜你喜欢
  • 1970-01-01
  • 2016-08-19
  • 2015-08-11
  • 2018-11-30
  • 2019-04-25
  • 2020-12-21
  • 1970-01-01
  • 2020-06-27
  • 2012-12-14
相关资源
最近更新 更多