无法从对象 Laravel 中检索字段值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18666292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:23:41  来源:igfitidea点击:

unable to retrieve field values from object laravel

phplaravellaravel-4

提问by arrowill12

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?

我无法获取要显示的应用程序的 id,但是当我删除 '->id' 说明符时,我可以获得一个包含所有字段的 json 对象。为什么会这样?

I should also note that the $host->physical_machine_nameworks fine.

我还应该注意到$host->physical_machine_name效果很好。

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.

我也无法使用预先加载,因为我在我的关系中使用了自定义外键。

回答by Sergiu Paraschiv

You are defining appsas a hasManyrelationship. This means appswill be a collection of entities, not a single one, hence the Illuminate\Database\Eloquent\Collectioninstance, 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 Appentity on it.

你定义apps为一种hasMany关系。这意味着apps将是实体的集合,而不是单个实体,因此是Illuminate\Database\Eloquent\Collection实例,因为 Laravel 将此类用于 Eloquent 填充的实体列表。作为实体的集合,您不会拥有该App实体的任何属性。

Instead of echo $host->app->id;you can

而不是echo $host->app->id;你可以

foreach($host->app as $app) {
    echo $app->id;
}