php - 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
解决方案
要获取campaings 行,您需要在->get()
查询末尾添加:
Party::find($id)->campaigns()->get();
或者
Party::find($id)->campaigns;
推荐阅读
- google-cloud-platform - 在 GCP 中关闭结算帐户和禁用结算帐户有什么区别?
- wordpress - “post_per_page”不显示指定的帖子数
- java - Class.forName(“org.postgresql.Driver”) 在加载 PostgreSQL Driver 时抛出 ClassNotFoundException()
- python - 为什么两台 Mac 电脑对 tkinter 事件的响应不同?
- xml - xml 到文件夹 vb.net
- angular - 关闭关闭时,有没有办法使 mat-dialog 的背景可点击?
- c# - Dapper、Postgres 和 camelcase
- javascript - 如何使用同一函数中的值创建表格并将值设置为表格单元格
- r - 调整 ggplot 图例和值
- java - 类的方法中类的引用