Laravel雄辩关系数据检索
我有下面的代码从数据库中获取数据Laravel雄辩关系数据检索,laravel,eloquent,Laravel,Eloquent,我有下面的代码从数据库中获取数据 $profile = Profiles::find(1); $currency = Profiles::find($profile->currency_id)->currency; 然后在模型中创建一个关系,如下所示 class Profiles extends Model { use HasFactory; protected $table = 'Profiles'; protected $primaryKey =
$profile = Profiles::find(1);
$currency = Profiles::find($profile->currency_id)->currency;
然后在模型中创建一个关系,如下所示
class Profiles extends Model
{
use HasFactory;
protected $table = 'Profiles';
protected $primaryKey = 'profile_id';
public function Currency()
{
return $this->belongsTo(Currencies::class, 'currency_id');
}
}
class Currencies extends Model
{
use HasFactory;
protected $table = 'Currencies';
protected $primaryKey = 'currency_id';
public function profile()
{
return $this->hasOne(Profiles::class, 'currency_id');
}
}
问题是只有1个配置文件和100种货币,currency\u id
是Profiles
表中的外键
我无法获取数据并获取此错误,试图获取非对象的属性“currency”
如果我使用$currency=Profiles::find(1)->currency;
,那么它将检索currency
表的第一行,该行不是必需的数据
如何获取该特定配置文件的货币行?问题是
find()
方法将查找primaryKey
,在您的第二次调用中,currency\u id
不是pk。
为您提供两种解决方案:
- 将查找替换为
子句,如:where
$currency=Profiles::where('currency\u id',$profile->currency\u id)->value('currency')
- 或者通过关系
$currency=$profile->currency;
Profiles::find($profile->currency\u id)
?$prof\u data=Profiles::find(1);$currencyAll=$pro_data->currency;@BABAKASHRAFI,因为我不清楚find将接受什么,如果我通过1,那么它总是会找到currency表的第一行,profile have currency_id=53,我需要从currency
表中获取currency_id=53的所有详细信息。@jrcode您应该将profile表的id传递给profile类,而不是currency。这将为你赢得整排的收入you@BABAKASHRAFI,你的意思是?restoprofile::find($restoprofile->profile\u id)->currency;
当我的profile\u id=1时,它总是返回货币的第一行,在我的profile中有currency\u id
,其值为53
,我需要从currences
@mi59中检索,这会从currences表中检索数据吗?我需要的是获取分配给profile的id的货币,y确切地说,请查看文档,以了解有关归属于
关系的更多详细信息