【问题标题】:RelationShip BelongsToMany Laravel - Only return withTimeStampsRelationShip BelongsToMany Laravel - 仅返回带有时间戳
【发布时间】:2021-10-29 07:04:55
【问题描述】:

我需要你的帮助。

我有下一个模型:

class Store extends Model {
    public function categories()
    {
        return $this->belongsToMany(Category::class,'category_by_store','store_id','category_id')->withPivot('refIdInMyStore');
    }
}

class Category extends Model{
public function store()
    {
        return $this->belongsToMany(Store::class, 'category_by_store','category_id','store_id');
    }}

所以,如果我想从我写的商店中检索类别:

$store = Store::find(1);
$categories = $store->categories()

但是回复是:{"withTimestamps":false}

¿我的错误是什么?

谢谢!

【问题讨论】:

  • $categories = $store->categories()更改为$categories = $store->categories

标签: php laravel relationship


【解决方案1】:

这是因为您将其作为函数调用$store->categories()。这类似于调用Categories::where('store_id', $id) 而不调用->get() 来执行查询。

您应该将其称为属性$categories = $store->categories

许多人反对不明确说明您正在执行新查询这一事实,因为关系看起来像一个属性。

我发现像这样使用急切加载会更好地提高代码清晰度和可能的性能:

$store = Store::with('categories')->find(1);

我相信这清楚地表明您将使用类别关系。

【讨论】:

  • 非常感谢@Azeame!我现在明白了!
  • 也为您添加更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 2020-09-19
  • 2014-11-23
  • 1970-01-01
  • 2018-07-09
  • 2020-12-25
  • 2020-11-23
相关资源
最近更新 更多