簡體   English   中英

Laravel 屬於不工作

[英]Laravel belongsTo not working

我的應用程序中有 2 個模型,“用戶”和“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

您的關系不起作用的原因不是因為模型中指定的關系,而是因為 User 模型中的方法命名而不是指定外鍵。

代替:

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;

這成功地返回了相關的medicine_type 的名稱。

我希望這能幫助你進一步;)

也許 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');
    }
}

我犯了一個愚蠢的錯誤,沒有在關系方法中添加“返回”!

請確保您返回的關系......很明顯,這行不通的:

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

我將“medicine_type”更改為“medicineType”,一切正常...

在我的情況下,相關模型數據被刪除,laravel 在一般查詢中不會得到軟刪除數據。 要獲得軟刪除的數據,您必須使用“withTrashed() 或 onlyTrashed()”。

您可以在此處查看文檔。

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

在大多數情況下,投票第一的答案可能是最佳答案。 但是,如果您仍然無法加載相關關系並且沒有運氣..

還有一件事可能有效。 查看模型的每個表及其索引或外鍵。 就我而言,我更改了表名,但從未更新涉及的索引和外鍵。

解決方案。

A:(感覺很懶)只要刪除關聯的索引或外鍵即可。

B:(我不是懶惰)通過laravel遷移刪除表並使用適當的外鍵重新運行artisan migrate。

模型:

class User extends Eloquent {

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

用戶控制器.php

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

foreach ($users as $user) {
    echo $user->medicine_type->name;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM