Eloquent 如何处理关系?

How Eloquent work with Relationship?

我是 laravel 关系的新手,如果这只是一个愚蠢的问题,那么很多人表示歉意。我在项目中使用名为 users_email 的枢轴 table 来获取用户的电子邮件。 Pivot table 包含外键 Uid 和 Email_id。 Uid 引用用户 table 主键与Email_id相同。我可以在使用 QueryBuilder 加入他们时得到结果。

 $recent_inbox_email=DB::table('users_email')->
                join('email','users_email.email_id','=','email.Id')->
                join('users','users_email.Uid','=','users.Id')->
                where('users_email.Uid','=',$Uid)->
                where('email.draft','<>','true')->
                where('email.trash','<>','true')->
                where('email.status','=','unread')->count();

这是我在模型中定义关系的方式

   public function getUid()//User Model
    {   
        return $this->hasMany("User_Email",'Uid');
    }

   public function getEmId()//Email Model
    {   
        return $this->hasMany("User_Email",'email_id');
    }
   //User_Email Model
    public function email()
   {
     return $this->belongsTo('Email','Id','email_id');
   }
   public function user()
  {
    return $this->belongsTo('User','Id','Uid');
  }

现在我想使用 Eloquent

查询类似的内容
    $query= select * from users_email inner join  
     email on users_email.email_id=email.Id
     inner join users on users_email.Uid=users.Id
     where users.Id=users_email.Uid limit 0,10

     foreach($query as $emails)
     {
      echo  $emails->f_name;
      echo $emails->Message
     }

数据库设计师图片 Link to image

谢谢

没有愚蠢的问题。我会尽力给你一个解释!我不是专业人士,但也许我可以提供帮助。 Laravel 使用了一些非强制性的约定,但如果您使用它们,事情就会变得很有魅力。 例如,作为一般建议,tables 应该以复数形式命名(您的 table 用户可以。您的 "email" table 应该是 "emails")。型号,应以单数命名。这是 table 用户的 User.php,table 电子邮件的 Email.php。 "The pivot table is derived from the alphabetical order of the related model names...",在本例中为 "email_user"。我再说一遍,您不必像这样命名它们,因为您可以为模型指定 table,在模型中设置 $table 属性。 一旦你设置了这样的东西,你只需要将它添加到你的用户模型中:

public function emails()
{
    return $this->belongsToMany('Email');
}

并且在您的电子邮件模型中:

public function users()
{
    return $this->belongsToMany('User');
}

括号内的"User"和"Email"为相关机型名称

就是这样。您现在可以这样做:

$user = User::find(1);
foreach($user->emails as $email) {
    echo $email->subject . '<br>';
    echo $email->message . '<br>';
}

如果您决定不遵循约定,您仍然可以使用 Eloquent 关系。您必须这样设置关系:

public function nameOfRelation()
{
    return $this->belongsToMany('NameOfRelatedModel', 'name_of_table', 'foreign_key', 'other_key');
}

以用户模型为例:

    public function emails()
    {
        return $this->belongsToMany('Email', 'users_email', 'Uid', 'email_id');
    }

而在电子邮件模型中,则相反。 答案很长!我没有测试代码,但这应该给你一个想法! 您可以随时查看官方 Laravel 文档,这真的很有帮助! http://laravel.com/docs/4.2/eloquent

希望我有所帮助