<?php
class Cat extends Eloquent {
    public function user() {
        return $this->belongsTo('User');
    }
}
class User extends Eloquent {
    public function cats() {
        return $this->hasMany('Cat');
    }
}
Run Code Online (Sandbox Code Playgroud)
现在:
$cats = Cat::with('user')->get();
Run Code Online (Sandbox Code Playgroud)
执行2个查询:
select * from `cats`
select * from `users` where `users`.`id` in ('1', '2', 'x')
Run Code Online (Sandbox Code Playgroud)
为什么不能这样做:
select * from cats inner join users on cats.user_id = users.id
Run Code Online (Sandbox Code Playgroud)
对于那些说表中有两个id列的人来说,使用别名可以很容易地避免这种情况:
select 
    c.id as cats__id,
    c.name as cats__name,
    c.user_id as cats__user_id,
    b.id as users__id,
    b.name as users__name
from cats c
inner join …Run Code Online (Sandbox Code Playgroud) 楷模
class WPModel extends Eloquent
{
    protected $table = 'work_processes';
    protected $guarded = array('id');
    protected $softDelete = true;
    // declaring one-to-many relationship
    public function relatedWPAQs()
    {
        return $this->hasMany('WPAQModel', 'wp_id');
    }
    public function relatedUsers()
    {
        return $this->belongsTo('UserModel', 'wp_owner_id');
    }
}
class UserModel extends Eloquent 
{
    protected $table = 'users';
    protected $softDelete = true;
    public function relatedWPs()
    {
        return $this->hasMany('WPModel', 'wp_owner_id');
    }
}
class WPAQModel extends Eloquent
{
    protected $table = 'wp_audit_questions';
    protected $fillable = array('wp_id', 'wp_audit_question');
    // declaring one-to-many relationship - …Run Code Online (Sandbox Code Playgroud)