I've database with a 3 tables.
- Campaigns
- Subscribers
- Campaign_subscribers (pivot table)
campaign
public function subscribers(): BelongsToMany
{
return $this->belongsToMany(Subscriber::class);
}
subscriber
public function campaigns(): BelongsToMany
{
return $this->belongsToMany(Campaign::class);
}
CampaingSubscriber
public function campaigns()
{
return $this->belongsTo(Campaign::class);
}
public function subscribers()
{
return $this->belongsTo(Subscriber::class);
}
migration
$table->unsignedBigInteger('campaign_id');
$table->foreign('campaign_id', 'campaign_id_fk_4864216')->references('id')->on('campaigns')->onDelete('cascade');
$table->unsignedBigInteger('subscriber_id');
$table->foreign('subscriber_id', 'subscriber_id_fk_4864216')->references('id')->on('subscribers')->onDelete('cascade');
tries
$subscribers = Campaign::with('subscribers')->where('id', 127)->get();
This returns collection with Campaign, with another collection of all subscribers of this campaign
I've tried several ways for search any subscriber, with = and like, buit not work,.
use Illuminate\Database\Eloquent\Builder;
$subscribers = Campaign::with('subscribers')->where('id', 127)->whereHas('subscribers', function($q) { $q->where('email','like', '%mateos@mydomain%');})->get();
This return the same result that original query.
Also, below fails, and showing all records of de campaing.
$subscribers = Campaign::with('subscribers')->where('id', 127)->whereHas('subscribers', function($q) { $q->where('email','=', 'email@included_:in_results');})->get();
Apreciate help.