Sunday, February 11, 2018

laravel one to on hasOne relationship manual foreign key and local key detecting wrong column - development

laravel one to on hasOne relationship manual foreign key and local key detecting wrong column

I have two tables

enter image description here

enter image description hered

In above table, I want to search countries.user_name (primary key) and want its isd code from isdcodes.code where isdcodes.country_username is the foreign key.

Country Model:

<?php
namespace App;

use IlluminateDatabaseEloquentModel;

class Country extends Model
{
protected $primaryKey = 'my_id';

public function isdcode(){
    return $this->hasOne('AppIsdcode', 'country_username', 'user_name');
} 
}

Route File

Route::get('user/{country}', function ($country){
    return AppCountry::find($country)->isdcode;
});

hear I am trying to search india(user_name in countries table)
http://localhost:8000/user/india
Trying to get property of non-object
the above result is coz it is trying to search india in my_id but I want to search it in user_name.

http://localhost:8000/user/1
{“isd_id”:1,”country_username”:”india”,”code”:91,”created_at”:null,”updated_at”:null}

Really thank you in advance.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-one-to-on-hasone-relationship-manual-foreign-key-and-local-key-detecting-wrong-column/
via Lzo Media

No comments:

Post a Comment