简体   繁体   English

调用归属返回null laravel

[英]invoke belongsTo return null laravel

the tables in the database are address 'address_type_id', 'address_type_id', 'line1', 'line2', 'line3', 'country', 'city', 'zip_code', 'other_detail', 'geo_location_id' 数据库中的表是地址'address_type_id','address_type_id','line1','line2','line3','country','city','zip_code','other_detail','geo_location_id'

address type table 'address_type_id' 'address_type_name' 地址类型表'address_type_id''address_type_name'

here is my models 这是我的模特

public function Users(){
    return $this->hasOne('User','address_id');
}

public function Address_Type(){
    return $this->belongsTo('Address_Type','address_type_id','address_type_id');
}

public function Geo_Location(){
    return $this->belongsTo('Geo_Location','geo_location_id','geo_location_id');
}

} }

public function Address(){
    return $this->hasMany('Address','address_type_id','address_type_id');
}

} }

and in Controller when i'm trying to get Address type like this 在控制器中,当我尝试获取这样的地址类型时

$address1=Address::find(1);

$geo=$address1->Geo_Location;
return Response::json(
    array(
        'error'   => false,
        'Address_Type' =>$address1->Address_Type),

    200
);

}); }); the result returns null 结果返回null

The issue is the naming of your relationship methods. 问题是您的关系方法的命名。 When doing $address1->Address_Type this is what happens: 在执行$address1->Address_Type ,将发生以下情况:

First, __get() in Illuminate\\Database\\Eloquent\\Model is called, which proxies off to getAttribute() . 首先, __get() Illuminate\\Database\\Eloquent\\Model __get() ,它替代了getAttribute() In there it first checks for a few other things and then there's this: 在这里,它首先检查其他一些内容,然后是:

$camelKey = camel_case($key);

if (method_exists($this, $camelKey))
{
    return $this->getRelationshipFromMethod($key, $camelKey);
}

As you can see the attribute name Address_Type get's converted into camelCase. 如您所见,属性名称Address_Type被转换为camelCase。 It becomes addressType . 它成为addressType

Now while PHP doesn't care if it's AddressType or aDdReSsTyPe an underscore makes a difference. 现在,尽管PHP不在乎它是AddressType还是aDdReSsTyPe ,但下划线会aDdReSsTyPe

The solution 解决方案

Change your relationship names. 更改您的关系名称。 I suggest addressType , geoLocation but as I mentioned before, the only important thing is that you lose the _ . 我建议使用addressTypegeoLocation但是正如我之前提到的,唯一重要的是您丢失了_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM