简体   繁体   中英

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 table '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

The issue is the naming of your relationship methods. When doing $address1->Address_Type this is what happens:

First, __get() in Illuminate\\Database\\Eloquent\\Model is called, which proxies off to 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. It becomes addressType .

Now while PHP doesn't care if it's AddressType or aDdReSsTyPe an underscore makes a difference.

The solution

Change your relationship names. I suggest addressType , geoLocation but as I mentioned before, the only important thing is that you lose the _ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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