首页 > 解决方案 > Eloquent OneToMany Relationships challenge

问题描述

I'm building an application using Lumen 5.8 and have a very simple model as follow:

class Party extends Model {

    protected $table = 'party';

    public function campaigns(){
        return $this->hasMany('App\Campaign');
    }

}

class Campaign extends Model {

    protected $table = 'campaign';

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

}

And my tables are defined as follow:

party (id,name)

campaign (id,name,party_id)

When I use the find method on Campaign or Party it returns the right rows. However if I try to use the relationship and get all campaigns a party has it never returns a row.

I tried the following code:

$campaings = Party::find($id)->campaigns();

and result is empty! But if I use the following I can get all campaigns:

$campaings = Campaign::where('party_id' , $id)->get();

What is that I'm not doing right?

Thanks

标签: phpeloquentlumen

解决方案


要获取campaings 行,您需要在->get()查询末尾添加:

Party::find($id)->campaigns()->get();

或者

Party::find($id)->campaigns;

推荐阅读