【问题标题】:Why do I get "Non-static method App\Models\Category::products() should not be called statically" in laravel为什么我在 laravel 中得到“不应静态调用非静态方法 App\Models\Category::products()”
【发布时间】:2018-11-02 14:09:19
【问题描述】:

模型类别.php

public function products() {
    return $this->belongsToMany('App\Models\Product', 'category_product', 'category_id', 'product_id')->withTimestamps();
}

模型产品.php

public function categories() {
    return $this->belongsToMany('App\Models\Category', 'category_product', 'product_id', 'category_id')->withTimestamps();
}

HomeController.php

$category = Category::products()->find($id);
return view('site.category.details',[
    'details' => $category
]);

details.blade.php

@dd($details->pivot->name)

【问题讨论】:

  • 因为您正在调用非静态方法,就好像它是静态方法一样。这里Category::products()->find($id);

标签: php laravel eloquent pivot pivot-table


【解决方案1】:

当您为给定类别定义belongsToMany 关系时,该关系定义了该关系。但是通过致电Category::products()...,您还没有说明您想要为哪个类别获取产品。

你可以通过$category = Category::find($category_id) 获取类别,然后通过$category->products 检索该类别的产品。你当然可以直接购买这样的产品:Category::find($category_id)->products

如果您致电->products,您将获得产品的结果集合。如果您使用括号 ->products() 调用它,那么您将返回 DB 查询类,然后您可以添加更多查询方法,例如:->products()->where('id', $product_id)->get()

所以我想您可能只是将->find($id) 放在->products() 之后而不是之前。

【讨论】:

  • 是的,我认为你是对的,会是这样的Category::find($category_id)->products()->find($id)
【解决方案2】:

如果你想在一个类别上加载“产品”,你可以这样做:

$category = Category::with('products')->find($id);

或者其他方式:

$category = Category::find($id)->load('products');

你可以在herehere看到这两种方法的区别。

【讨论】:

    【解决方案3】:

    警告是因为 $this 在静态方法调用中不可用,并且如果方法未声明为静态,则很可能有人可以将 $this 语句添加到此方法中,而不是期望在某处静态调用。

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2023-02-22
      • 2019-12-02
      • 2014-09-08
      • 1970-01-01
      相关资源
      最近更新 更多