Reputation: 1804
I am trying to use eloquent relationships to retrieve some data from my DB. I am running into an issue when trying to get specific fields rather than the full object. Here is some of my code.
Controller:
public function getHosts($table = null)
{
foreach (Hosts::all() as $host)
{
echo $host->physical_machine_name;
echo $host->app->id;
}
}
models:
class Hosts extends Eloquent
{
protected $connection = 'mysql_2';
protected $table = 'hosts';
public $timestamps = false;
public function app(){
return $this->hasMany('Apps', 'os_instance_name')->orWhere('os_instance_name', $this->os_instance_name);
}
}
class Apps extends Eloquent
{
protected $connection = 'mysql_2';
protected $table = 'app_instances';
public $timestamps = false;
public function host()
{
return $this->belongsTo('Hosts','os_instance_name')->orWhere('os_instance_name', $this->os_instance_name);
}
}
I am not able to get the id of the app to display but when I remove the '->id' specifier i am able to get a json object containing all of the fields. Why is this happening?
I should also note that the $host->physical_machine_name
works fine.
this is the error I receive:
Undefined property: Illuminate\Database\Eloquent\Collection::$id
I am also unable to use eager loading because I am using custom foreign keys in my relationships.
Upvotes: 2
Views: 9606
Reputation: 10153
You are defining apps
as a hasMany
relationship. This means apps
will be a collection of entities, not a single one, hence the Illuminate\Database\Eloquent\Collection
instance, as Laravel uses this class for lists of entities populated by Eloquent.
Being a collection of entities you won't have any properties of the App
entity on it.
Instead of echo $host->app->id;
you can
foreach($host->app as $app) {
echo $app->id;
}
Upvotes: 7