dev*_*r34 1 eager-loading laravel eloquent laravel-4
我是laravel的新手,并创建一个基本的应用程序来控制关系.我实现了一对一的关系,并希望从基表和相关表中获取特定的列.我有两个表,即users和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');
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试检索所有列时,一切正常
$users = User::with('identity_cards')->get()->toArray();
Run Code Online (Sandbox Code Playgroud)
但是当我试图从其中一个或两个表中获取特定列时,我得到一个空数组来对抗身份证表的记录
$users = User::with(array('identity_cards'),function($query) {
$query->select('issuance_location'); //getting specific column from identity card table
}
)->get(array("first_name"))->toArray();
Run Code Online (Sandbox Code Playgroud)
针对以上陈述的结果如下: -
Array
(
[0] => Array
(
[first_name] => User1
[identity_cards] =>
)
[1] => Array
(
[first_name] => User2
[identity_cards] =>
)
[2] => Array
(
[first_name] => User3
[identity_cards] =>
)
)
Run Code Online (Sandbox Code Playgroud)
这可以使用查询生成器实现,但我想要解决方案eloquent.为什么我得到一个空数组为我的相关表,即使我有数据.如何使用急切加载获取特定列?
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();
Run Code Online (Sandbox Code Playgroud)
3我会重新命名这种关系identity_card,因为hasOne它会更容易使用.
| 归档时间: |
|
| 查看次数: |
1427 次 |
| 最近记录: |