問題描述
我的應(yīng)用中有 2 個模型,用戶"和'MedicineType'(每個用戶屬于一個 MedicineType).
I have 2 models in my app, 'User' & 'MedicineType' (each User belongs to one MedicineType).
我使用belongsTo() 和hasMany() 在兩個模型之間建立了一對多關(guān)系.hasMany() 關(guān)系完美運(yùn)行,但belongTo() 不起作用.有誰知道我哪里出錯了?
I made the one-to-many relation between two model using belongsTo() and hasMany(). hasMany() relation works perfectly but belongTo() doesn't work. Does anyone know where did I make a mistake?
User::find(1)->medicine_type [這不返回任何內(nèi)容]
User::find(1)->medicine_type [this returns nothing]
MedicineType::find(1)->users [返回用戶]
MedicineType::find(1)->users [this returns users]
這是模型的代碼:
class MedicineType extends Eloquent {
public function users()
{
return $this->hasMany('User');
}
}
class User extends Eloquent {
public function medicine_type()
{
return $this->belongsTo('MedicineType');
}
}
這是我的數(shù)據(jù)庫結(jié)構(gòu):
users:
id
name
medicine_type_id
medicine_types:
id
name
推薦答案
你的關(guān)系不工作的原因不是因為模型中指定的關(guān)系,而是因為 User 模型中的方法命名而不是指定外部鍵.
The reason your relation is not working is not because of the relations specified in the model, but because of the method naming in the User model and not specifying the foreign key.
代替:
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;
這成功返回了相關(guān)的medicine_type 的名稱.
This successfully returns the related medicine_type's name.
我希望這能幫助你進(jìn)一步;)
I hope this helps you further ;)
這篇關(guān)于Laravel 屬于不工作的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!