sapef44489
sapef44489

Reputation: 69

laravel 5 Search related models

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

Answers (2)

AH.Pooladvand
AH.Pooladvand

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

Bohdan Petrenko
Bohdan Petrenko

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

Related Questions