Array returning null value, many to many. laravel

孤者浪人 提交于 2019-12-13 06:14:42

问题


I'm trying to retrieve data from many to many relationship.I have two tables :

companies: [cid,name,origin]

vehicle_types: [id, type]

their pivot table: companies_vehicle_types: companies_id,vehicle_types_id Relationship defined: In Companies:

class companies extends Model
{
    //
    protected $fillable = ['name','origin'];
    protected $primaryKey = 'cid';


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

public function vehicle_types(){

     return $this->belongsToMany('App\vehicle_types', 'companies_vehicle_types', 'companies_id', 'vehicle_types_id');
}
}

In vehicle_types

class vehicle_types extends Model
{
    //
    protected $fillable = ['type'];

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

public function companies(){

    return $this->belongsToMany('App\companies','companies_vehicle_types','vehicle_types_id','companies_id')->withTimestamps();
}
}

I want to retrieve companies where vehicle_types = specific type. How can i do that? I tried doing following in my controller:

$vehicle_types=vehicle_types::where('type','Bike')->get();
    foreach ($vehicle_types as $vehicle_type) {
               # code...
            foreach ($vehicle_type->companies as $company) {
                     $brand[]=$company->pivot->name;
                }
           }
                return $brand;

But it doesn't seem to be working. $vehicle_types is working fine and returning value. $brand is not returning any value.

来源:https://stackoverflow.com/questions/41789718/array-returning-null-value-many-to-many-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!