【发布时间】:2014-11-12 10:43:57
【问题描述】:
我是 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 的解决方案。为什么即使我的相关表中有数据,我也会得到一个空数组。如何使用预先加载获取特定列?
【问题讨论】:
标签: laravel laravel-4 eloquent eager-loading