代码之家  ›  专栏  ›  技术社区  ›  Hemant Maurya

laravel one to on HASON关系手动外键和本地键检测错误列

  •  1
  • Hemant Maurya  · 技术社区  · 7 年前

    我有两张桌子

    enter image description here

    enter image description hered

    在上表中,我要搜索 国家。user\u名称 (主键)并希望其isd代码来自 ISD代码。密码 哪里 ISD代码。country\u用户名 是外键。

    国家/地区模式:

    <?php
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Country extends Model
    {
    protected $primaryKey = 'my_id';
    
    public function isdcode(){
        return $this->hasOne('App\Isdcode', 'country_username', 'user_name');
    } 
    }
    

    路由文件

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

    听说我正在尝试搜索印度(user\u name in countries表) http://localhost:8000/user/india 尝试获取非对象的属性 上面的结果是因为它试图在my\u id中搜索印度,但我想在user\u name中搜索它。

    http://localhost:8000/user/1 {“isd\U id”:1,“country\u username”:“india”,“code”:91,“created\u at”:null,“updated\u at”:null}

    真的提前谢谢你。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Alexey Mezenin    7 年前

    find() 方法使用主键,因此需要将其更改为:

    return \App\Country::where('user_name', $country)->first()->isdcode;
    

    或者,如果要将此列用作主键,请执行此操作:

    protected $primaryKey = 'user_name';