获得具有热切加载laravel 4的特定列

时间:2014-09-18 07:32:58

标签: laravel laravel-4 eloquent eager-loading

我是laravel的新手,并创建一个基本的应用程序来控制关系。我已经实现了一对一的关系,并希望从基表和相关表中获取特定的列。我有两个表,即用户和identity_cards.Relationship定义如下

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
     protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    //protected $hidden = array('password', 'remember_token');

    protected $fillable = array('first_name','last_name','email','created_at','updated_at');

    public function identity_cards() 
    {
        return $this->hasOne('IdentityCard');
    }
}


class IdentityCard extends Eloquent {

    protected $table    = 'identity_cards';
    protected $fillable = array('issuance_date','expiry_date','issuance_location','user_id');
    public $timestamps  = false;

    public function user()
    {
       return $this->belongsTo('User');
    }
}

当我尝试检索所有列时,一切正常

$users = User::with('identity_cards')->get()->toArray();

但是当我尝试从其中一个或两个表中获取特定列时,我在身份证表的记录中得到一个空数组

 $users = User::with(array('identity_cards'),function($query) {
                $query->select('issuance_location'); //getting specific column from identity card table
              }
          )->get(array("first_name"))->toArray();

针对上述陈述的结果如下: -

Array
(
    [0] => Array
    (
        [first_name] => User1
        [identity_cards] => 
    )

    [1] => Array
    (
        [first_name] => User2
        [identity_cards] => 
    )

    [2] => Array
    (
        [first_name] => User3
        [identity_cards] => 
    )

 )

这可以使用查询构建器来实现,但我希望解决方案具有eloquent。为什么我得到一个空数组用于我的相关表,即使我有数据。如何使用急切加载获取特定列?

2 个答案:

答案 0 :(得分:7)

1您需要始终选择父亲的primary key和关系子女的foreign key,否则Eloquent将无法匹配相关模型。

2传递给eager loading的Closure是数组的值,而不是with函数的第二个参数:

User::with(array('identity_cards' => function($query) {
            $query->select('issuance_location', 'user_id');
      }))->get(array('first_name', 'id'))->toArray();

3我会将该关系重命名为identity_card,因为它hasOne - 它会更容易使用。

答案 1 :(得分:0)

解决方案之一就是创建一个类似于你所做的新关系,但稍微调整一下,对于客户来说:

public function identity_cards_limited() 
    {
        return $this->hasOne('IdentityCard')->select('desired_column');
    }
相关问题