Laravel渴望加载一对多的关系

时间:2014-10-20 06:11:20

标签: php laravel eager-loading

美好的一天,我遇到了这个问题,我试图从2个表中检索记录

eager loading

class Leads extends Eloquent
{
    public function leademail()
    {
        return $this->hasMany('LeadDetailEmails'); 
    }
}

class LeadDetailEmails extends Eloquent
{
    public function lead()
    {
        return $this->belongsTo('Leads');
    }
}


class Category extends BaseController
{
    public function fetchRecord()
    {
        $result = Leads::with('leademail')->get();
    }
}

leadDetailEmails在迁移文件中设置了外键

$table->foreign('lead_id')->references('id')->on('leads')->onDelete('cascade');

我收到此错误:

"message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'lead_detail_emails.leads_model_id' in 'where clause' (SQL: select * from `lead_detail_emails` where `lead_detail_emails`.`leads_model_id` in (1, 2, 3))"

我该怎么做才能解决错误?另外,如果有第三个表(LeadDetailContact),我怎么能急于加载表?

感谢。

1 个答案:

答案 0 :(得分:0)

您应该尝试按以下方式为LeadDetailEmails指定表名:

class LeadDetailEmails extends Eloquent
{
    protected $table = 'leadDetailEmails';

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

如果您希望通过热切加载获得更多关系,您可以这样做:

$result = Leads::with('leademail', 'leadcontact')->get();