Reputation: 69
I have two related model.
class Girl extends Model
{
public function target()
{
//return $this->hasOne('App\Target');
return $this->belongsToMany('App\Target', 'girl_target', 'girl_id',
'target_id');
}
}
And
class Target extends Model
{
public function girl()
{
return $this->belongsToMany('App\Girl', 'girl_target');
}
}
How I can find girl model by related target id?
$girls = Girl::where('banned', 0)
->with('target');
$targets=$seachSettings->target()->get();
if($targets!=null){
foreach ($targets as $item) {
// $girls->target()->array_where();
$girls->target()->where('girl_target','target_id',$item->id);
}
}
I want get only models where related targets with id from my $targets array.
Upvotes: 0
Views: 34
Reputation: 2059
You need to use whereHas()
method
$girls = Girl::whereHas('target', function ($query) use($item) {
$query->where('id', $item->id);
})->where('banned', 0)->with('target');
Upvotes: 2
Reputation: 380
define the relationship between Girl
and Target
class Girl extends Model
{
public function target(): HasMany
{
return $this->hasMany('App\Target', 'foreign_key', 'local_key');
}
}
class Target extends Model
{
public function girl(): BelongsTo
{
return $this->belongsTo('App\Girl', 'foreign_key', 'local_key');
}
}
and then if u want to get girl targets, just call
$targets = Girl::find(1)->target;
or if u want to get girl by target
$girl = Target::find(1)->girl;
Upvotes: 0