Reputation: 123
I am new to laravel and making a basic application to get a grip on relationships.I have implemented one to one relationship and want to get specific columns from both the base table and the related table.I have two tables namely users and identity_cards.Relationship is defined as follows
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');
}
}
Everything works fine when i try to retrieve all the columns
$users = User::with('identity_cards')->get()->toArray();
But when i try to get specific columns from either or both the tables,i got an empty array against the record for identity card table
$users = User::with(array('identity_cards'),function($query) {
$query->select('issuance_location'); //getting specific column from identity card table
}
)->get(array("first_name"))->toArray();
Result against the above statement is as follows:-
Array
(
[0] => Array
(
[first_name] => User1
[identity_cards] =>
)
[1] => Array
(
[first_name] => User2
[identity_cards] =>
)
[2] => Array
(
[first_name] => User3
[identity_cards] =>
)
)
This can be achieved using query builder but i want the solution with eloquent.Why am i getting an empty array for my related table even if i have the data in it.How specific columns can be fetched using eager loading??
Upvotes: 1
Views: 1714
Reputation: 81187
1 You need to always select primary key
of the parent and foreign key
of the child of a relation, otherwise Eloquent won't be able to match related models.
2 Closure passed to the eager loading is a value of the array, not 2nd parameter of with
function:
User::with(array('identity_cards' => function($query) {
$query->select('issuance_location', 'user_id');
}))->get(array('first_name', 'id'))->toArray();
3 I would rename that relation to identity_card
, for it's hasOne
- it will be easier to work with.
Upvotes: 7
Reputation: 5755
One of the solution would be just making a new relation similar to that you have made, but tweaking it a bit, for conviniece :
public function identity_cards_limited()
{
return $this->hasOne('IdentityCard')->select('desired_column');
}
Upvotes: 0