简体   繁体   English

Laravel 5.4中的ORM无法正常工作

[英]ORM in laravel 5.4 not working

I have 2 tables "Items" and "brands". 我有2个表格“项目”和“品牌”。 items contains product details such as item_id, name and brand_id while brands contains brandId and brand_name. items包含产品详细信息,例如item_id,名称和brand_id,而brands包含brandId和brand_name。 I want to fetch Item data in which I can join brands and items. 我想获取可以加入品牌和商品的商品数据。

This is my controller. 这是我的控制器。

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

This is my model. 这是我的模型。

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

I got the following while running on my browser. 在浏览器上运行时,我得到了以下内容。 Using $this when not in object context 不在对象上下文中时使用$ this

Try like this : 尝试这样:

Model File : 模型文件:

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

And controller like this : 和像这样的控制器:

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

Remove the static keyword 删除静态关键字

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

in your Brands you need 在您的品牌中,您需要

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

and your controller: 和您的控制器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM