Laravel属于不工作

问题描述 投票:24回答:7

我的应用程序中有2个模型,'User'和'MedicineType'(每个用户属于一个MedicineType)。

我使用belongsTo()和hasMany()在两个模型之间建立了一对多关系。 hasMany()关系可以正常工作,但是belongTo()不起作用。有人知道我在哪里弄错了吗?

User :: find(1)-> medicine_type [这什么也没返回]

MedicineType :: find(1)-> users [返回用户]

这是模型的代码:

class MedicineType extends Eloquent {

    public function users()
    {
        return $this->hasMany('User');
    }
}


class User extends Eloquent {

    public function medicine_type()
    {
        return $this->belongsTo('MedicineType');
    }
}

这是我的数据库结构:

users:
    id
    name
    medicine_type_id 

medicine_types:
    id
    name
php laravel orm laravel-4 eloquent
7个回答
46
投票

您的关系不起作用的原因不是由于模型中指定的关系,而是由于用户模型中的方法命名且未指定外键。

而不是:

public function medicine_type()
{
    return $this->belongsTo('MedicineType');
}

用途:

public function medicineType()
{
    return $this->belongsTo('MedicineType', 'id');
}

我希望这对您有用;)

所有内容:

<?php // app/models/MedicineType.php

class MedicineType extends Eloquent {

   // Determines which database table to use
   protected $table = 'medicine_types';

   public function users() 
   {
      return $this->hasMany('User');
   }

}

和:

<?php // app/models/User.php

class User extends Eloquent {

   // Determines which database table to use
   protected $table = 'users';

   public function medicineType() 
   {
      return $this->belongsTo('MedicineType', 'id');
   }

}

测试是否有效:

$user = User::find(1);
return $user->medicineType->name;

这将成功返回相关的医学类型名称。

我希望这可以帮助您进一步;)


11
投票

也许Eloquent找到外键存在问题。试试这个:

class User extends Eloquent {

    public function medicine_type()
    {
        return $this->belongsTo('MedicineType', 'medicine_type_id');
    }
}

编辑:

此外,Eloquent尝试查找表“ medicinetypes”而不是“ medecine_types”,因此您还需要使用$table变量进行指定。

class MedicineType extends Eloquent {
    protected $table = 'medicine_types';

    public function users()
    {
        return $this->hasMany('User');
    }
}

3
投票

我犯了一个愚蠢的错误,没有在关系方法中添加“ return”!

确保您返回该关系...显然,这将not起作用:

public function medicineType() 
   {
      $this->belongsTo('MedicineType', 'id');
   }

1
投票

我将“ medicine_type”更改为“ medicineType”,一切正常...


0
投票

在我的情况下,相关模型数据已删除,而laravel在一般查询中不会获得软删除的数据。要获取软删除的数据,您必须使用“ withTrashed()或onlyTrashed()”。

您可以在这里查看文档。

https://laravel.com/docs/5.6/scout#soft-deleting


0
投票

在大多数情况下,票数第一的答案可能是最好的答案。但是,如果您仍然在加载相关关系时遇到麻烦,也没有运气。.

还有另一件事可能起作用。查看每个模型的表及其索引或外键。就我而言,我已更改了表名,但从未更新所涉及的索引和外键。

解决方案。

A:(Feeling Lazy)只需删除关联的索引或外键。

B :(我不是懒惰)通过laravel迁移删除表,并使用适当的外键重新运行artisan迁移。


0
投票

型号:

class User extends Eloquent {

    public function medicine_type()
    {
        return $this->belongsTo('MedicineType');
    }
}

UserController.php

$users= App\User::all();

foreach ($users as $user) {
    echo $user->medicine_type->name;
}
© www.soinside.com 2019 - 2024. All rights reserved.