简体   繁体   中英

laravel eloquent eager loading nested condition

I have 2 tables that is using eager loading and then using nested condition in that eager loading:

//migration for lead table
public function up()
{
    Schema::create('leads', function(Blueprint $table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('first_name',255);
        $table->string('surname',255);
    });

    Schema::table('leads', function($table)
    {
        $table->foreign('create_by')->references('id')->on('employees')->onDelete('cascade');
    });
}

//lead for lead detail emails
public function up()
{
    Schema::create('lead_detail_emails', function(Blueprint $table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('lead_id')->unsigned();
        $table->string('email',255);
    });

    Schema::table('lead_detail_emails',function($table)
    {
        $table->foreign('lead_id')->references('id')->on('leads')->onDelete('cascade');
    });
}

//leads model
class LeadsModel extends Eloquent
{
    protected $table = 'leads';

    public function emails()
    {
        return $this->hasMany('LeadDetailEmailsModel','lead_id','id');
    }
}

//lead detail emails
class LeadDetailEmail extends Eloquent
{
    protected $table = 'lead_detail_email';

    public function lead()
    {
        return $this->belongsTo('LeadsModel');
    }
}

When I am trying to add nested condition to eager loading, lets say

$qry = LeadsModel::with(
                            array
                            (
                            'emails' => function($qr)
                            {
                                $qr->orWhere('email','like','%testname%');
                            }
                       ));

$res = $qry->get();

dd($res);

It returns all the records in the lead, I have tried joining emails and $qry by using

->join('lead_detail_emails','lead_detail_emails.lead_id','=','leads.id');

but it does not work as well. may I know what is the problem in the code?

update question

how can i get the leads by doing nested condition on the emails?

$qry = LeadsModel::with(array('emails' => function ($q) use ($input) {
            $q->where('email','like',"%{$input}%");
        }))->whereHas('emails', function ($q) use ($input) {
            $q->where('email','like',"%{$input}%");
        });

$res = $qry->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM