Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

php - Laravel belongsTo not working

I have 2 models in my app, 'User' & 'MedicineType' (each User belongs to one MedicineType).

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 [this returns nothing]

MedicineType::find(1)->users [this returns users]

Here's the code to Models:

class MedicineType extends Eloquent {

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


class User extends Eloquent {

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

And here is my database structure:

users:
    id
    name
    medicine_type_id 

medicine_types:
    id
    name
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Instead of:

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

Use:

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

I hope this works for you ;)

Everything together:

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

}

and:

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

}

Testing if it works:

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

This successfully returns the related medicine_type's name.

I hope this helps you further ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...