我有三个模特。Sponsor,Optin和Participant。Sponsor和Optin有一对多的关系,Optin有一对一的Participant.
这使得模型看起来像这样:
赞助模式
class Sponsor extends Model
{
public function optins()
{
return $this->hasMany(Optin::class);
}
}Optin模型
class Optin extends Model
{
public function sponsor()
{
return $this->belongsTo(Sponsor::class);
}
public function participant()
{
return $this->belongsTo(Participant::class);
}
}参与者模型
class Participant extends Model
{
public function optins()
{
return $this->hasMany(Optin::class);
}
public function scopeCreatedToday($query)
{
return $query->whereDate('created_at', Carbon::today());
}
}现在,在一项每天预定的任务中,我想遍历今天创建的所有参与者,这些参与者选择了某个赞助商,像电子邮件或其他东西一样发送给他们。现在,我已经回到了属于参与者的身份。但是下一步是获取参与者对象,并通过正确的创建日期对它们进行筛选。但我有点不知所措。
$sponsor = Sponsor::find(1);
$count = $sponsor->optins()->count();
echo("Count: " . $count . "\n");
$optins = $sponsor->optins()->get();
foreach($optins as $optin)
{
echo($optin->participant_id . "\n");
}编辑:,在重新考虑了结构之后,我发现Optin与Participant有着多对一的关系。
发布于 2021-11-18 02:38:11
由于Participant与Optin有一对多的关系,所以我在Sponsor模型上添加了以下关系。通过传递Optin模型als,将第二个参数传递给belongsToMany方法,因为它作为中间表运行。
public function participants()
{
return $this->belongsToMany(Participant::class, Optin::class);
}通过添加属于赞助商的子查询,我可以轻松地获得所有参与者,如下所示:
$sponsor = Sponsor::find(1);
$participants = $sponsor->participants()->createdToday()->get();
foreach($participants as $participant)
{
//do something with $participant
}https://stackoverflow.com/questions/70010594
复制相似问题