【问题标题】:laravel one to on hasOne relationship manual foreign key and local key detecting wrong columnlaravel one to on hasOne 关系手动外键和本地键检测错列
【发布时间】:2018-07-21 21:38:23
【问题描述】:

我有两张桌子

在上表中,我想搜索 countries.user_name(主键)并希望从 isdcodes.code获得其 isd 代码> 其中 isdcodes.country_username 是外键。

国家模式:

<?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;
});

听说我正在尝试搜索印度(国家/地区表中的用户名) http://localhost:8000/user/india 试图获取非对象的属性 上面的结果是因为它试图在 my_id 中搜索印度,但我想在 user_name 中搜索它。

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

非常感谢您。

【问题讨论】:

  • 我认为主键和外键通常分配在 id 字段而不是文本字段上。

标签: php laravel laravel-5 foreign-keys relationship


【解决方案1】:

find() 方法使用主键,所以你需要把它改成这样:

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

或者这样做,如果你想将此列用作PK:

protected $primaryKey = 'user_name';

【讨论】:

  • 真的谢谢你,兄弟...它成功了,我不知道find方法到底是做什么的。 :)
猜你喜欢
  • 2020-07-14
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多