我有三個模型。Sponsor,Optin和Participant。與具有Sponsor一對多的關系Optin并且Optin具有一對一的關系Participant。
這使模型看起來像這樣:
贊助模式
class Sponsor extends Model
{
public function optins()
{
return $this->hasMany(Optin::class);
}
}
選擇模型
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());
}
}
現在,在每日計劃任務中,我想遍歷今天創建的所有參與者,并選擇加入某個贊助商以向他們發送電子郵件或其他內容。現在我得到了回應所屬參與者的 id。但下一步是獲取參與者物件并按正確的創建日期過濾它們。但我對如何處理這個有點迷茫。
$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.
uj5u.com熱心網友回復:
步驟 1 是使用關系定義Sponsor和Participant模型之間的belongsToMany關系。我假設您的optins表同時具有participant_id和sponsor_id列。
class Sponsor extends Model
{
public function optins()
{
return $this->hasMany(Optin::class);
}
public function participants()
{
return $this->belongsToMany(Participant::class, 'optins');
}
}
然后您想使用該with()方法預先加載關系,并根據您的創建日期條件對其進行過濾。這將使參與者作為集合可用。
$date = now()->subDay(); // or whatever you like.
$start = $date->startOfDay();
$end = $date->endOfDay();
$sponsor = Sponsor::where('id', 1)
->with([
'participants' => function($q) use ($start, $end) {
$q->whereBetween('participants.created_at', [$start, $end]);
}
])
->firstOrFail();
$count = $sponsor->participants->count();
echo("Count: $count\n");
foreach($sponsor->participants as $participant)
{
echo("$participant->name\n");
}
uj5u.com熱心網友回復:
如 miken32 答案中所述。由于Participant與Optin我有一對多的關系,我在Sponsor模型上添加了以下關系。將Optin模型作為第二個引數傳遞給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
}
uj5u.com熱心網友回復:
請嘗試定義所有模型的主鍵,并在使用函式時設定每個函式的外鍵
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/361378.html
上一篇:找出Joomla資料庫中使用的域
