Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel雄辩关系数据检索_Laravel_Eloquent - Fatal编程技术网

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;

为什么要将货币id传递给配置文件模型?这里是
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确切地说,请查看文档,以了解有关
归属于
关系的更多详细信息