简体   繁体   English

Laravel雄辩的关系无法访问第二张表

[英]Laravel eloquent relationship not accessing second table

I have 2 tables: 我有2张桌子:

emails: email_id, name 电子邮件:email_id,姓名

email_templates: template_id, template_mid, template_lang, template_subject, template_mail email_templates:template_id,template_mid,template_lang,template_subject,template_mail

Template_mid is foreign key and associated with emails.id Template_mid是外键,并且与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 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. 我无法访问模板方法,并且在转储结果中只有ID和主题。 How can I fix this? 我怎样才能解决这个问题?

Related models are not loaded automatically. 相关模型不会自动加载。 You can either load them with with() , or individually: 您可以with()加载它们,也可以单独加载:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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