简体   繁体   中英

Laravel eloquent relationship not accessing second table

I have 2 tables:

emails: email_id, name

email_templates: template_id, template_mid, template_lang, template_subject, template_mail

Template_mid is foreign key and associated with emails.id

My models:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Email extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * Indicates primary key column.
     *
     * @var bool
     */
    protected $primaryKey = "email_id";

    public function template()
    {
        return $this->hasOne('App\Email_template', 'template_mid', 'email_id');
    }
}

Email_template

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Email_template extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * Indicates primary key column.
     *
     * @var bool
     */
    protected $primaryKey = "template_id";
}

When I run this in my controller:

public function index()
    {

        $emails = Email::all();
        dd($emails);
    }

I cannot access the the template method and I have only id, subject in the dumped results. How can I fix this?

Related models are not loaded automatically. You can either load them with with() , or individually:

Email::with('template')->get();

or

foreach($emails as $email) 
{ 
      dd($email->template); 
}

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