Greetings,
I am refactoring a process to use pivot tables to keep my models clean and make life simpler for reporting and, so far, most everything is good. I am, however, having an issue with trying to use the pivot tables in a closure query.
I have two models:
class ThreatRisk extends Model
{
public function actions()
{
return $this->belongsToMany('App\ThreatRiskDataAction')->withPivot('name', 'date')->withTimestamps();
}
}
class ThreatRiskDataAction extends Model
{
public function threats()
{
return $this->belongsToMany('App\ThreatRisk')->withTimestamps();
}
}
Here is my pivot migration. As you can see I am passing additional columns with the pivot for ease of use.
Schema::create('threat_risk_threat_risk_data_action', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('threat_risk_id');
$table->unsignedBigInteger('threat_risk_data_action_id');
$table->text('name');
$table->text('date');
$table->timestamps();
});
Here is the data table for the data actions
ThreatRiskDataAction Table
id name created_at updated_at
1 Informed Student of Infraction 2020-11-18 08:35:50.247 2020-11-18 08:35:50.247
2 Bullying Investigation 2020-11-18 08:36:02.840 2020-11-18 08:36:02.840
3 Notified Student's Parents 2020-11-18 08:36:31.677 2020-11-18 08:36:31.677
4 Contacted Police 2020-11-18 08:36:49.327 2020-11-18 08:36:49.327
5 Notified Special Education 2020-11-18 08:37:01.177 2020-11-18 08:37:01.177
6 Person(s) Notified 2020-11-18 08:37:12.717 2020-11-18 08:37:12.717
7 Notified Victim(s) & Their Parents 2020-11-18 08:37:28.377 2020-11-18 08:37:28.377
I am trying to return all records that use the data action of Contacted Police. I have the following, which works, but I have a feeling that I should not have to pass in the threat_risk_data_action_id into the query. It seems like I should be able to use the name of the data action instead of the id :
$case5 = ThreatRisk::whereBetween('report_date', [$start, $end])
->where(function ($query) {
$query->whereHas('actions', function ($query){
$query->where('threat_risk_data_action_id', 4);
});
})
->count();
Thanks for your assistance and grace.