【问题标题】:ORM in laravel 5.4 not workinglaravel 5.4 中的 ORM 不起作用
【发布时间】:2017-10-17 06:10:45
【问题描述】:

我有 2 个表“项目”和“品牌”。 items 包含产品详细信息,例如 item_id、name 和 brand_id,而brands 包含 brandId 和 brand_name。我想获取可以加入品牌和商品的商品数据。

这是我的控制器。

public function filters($id){
    $items = Items::brands();       
    return $items;
}

这是我的模型。

public static function brands(){
    return $this->hasOne('App\Brands');
}

我在浏览器上运行时得到以下信息。 不在对象上下文中时使用 $this

【问题讨论】:

  • 你有一个静态方法并且你在其中使用了 $this 你认为会发生什么?

标签: php database join orm laravel-5.4


【解决方案1】:

去掉静态关键字

public function brand(){
    return $this->hasOne('App\Brands','brand_id');
}

在您需要的品牌中

public function item(){
    return $this->belongsTo('App\Items','brandId','brand_id');
}

和你的控制器:

public function filters($id){
    $items = Items::all()->with('brands')->get();       
    return $items;
}

【讨论】:

  • 我认为项目belongsTo 品牌
  • 我放的时候效果很好。公共函数brands(){ return $this->hasOne('App\Brands', 'brand_id', 'brand_id'); }
  • 你应该把它命名为brand,因为你有1:1 1 item 1 brand,
【解决方案2】:

试试这样:

模型文件:

public function brands(){
    return $this->hasOne('App\Brands');
}

还有这样的控制器:

public function filters($id){
    $items = Items::select("*")->with('brands')->get()->toArray();       
    return $items;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2017-12-13
    • 2017-12-04
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多