无法在Laravel 4中检索一对多关系

时间:2013-09-10 16:54:16

标签: php laravel laravel-4 relationship eloquent

我正在尝试通过我的用户模型访问ProfileType,即$ user-> profile-> profiletype;但是,我无法检索到某个对象。基本上,用户有一个配置文件,配置文件属于用户和配置文件类型。 ProfileType有很多个人资料。

我的表名是users,profiles和profile_types。

模型/ user.php的

use Cartalyst\Sentry\Users\Eloquent\User as SentryUserModel;

class User extends SentryUserModel {

    /**
     * Indicates if the model should soft delete.
     *
     * @var bool
     */
    protected $softDelete = true;

    public function profile()
    {
            return $this->hasOne('Profile');
    }
}

模型/ Profile.php

class Profile extends Eloquent {

    protected $fillable = array('username', 'slug', 'completed');

    /**
    * @return
    */
    public function user()
    {
            return $this->belongsTo('User');
    }

    public function profiletype()
    {
            return $this->belongsTo('ProfileType');
    }
}

模型/ ProfileType.php

class ProfileType extends Eloquent {

    /**
    * @return
    */
    public function profiles()
    {
            return $this->hasMany('Profile');
    }

}

Profile和ProfileType迁移

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

// profile_types table

class CreateProfileTypesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('profile_types', function(Blueprint $table) {
            $table->integer('id', true);
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('profile_types');
    }

}

// profiles table

class CreateProfilesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('profiles', function(Blueprint $table) {
            $table->integer('id', true);
            $table->string('username');
            $table->string('slug');
            $table->boolean('completed');
            $table->integer('user_id');
            $table->integer('profile_type_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('profiles');
    }

}

1 个答案:

答案 0 :(得分:1)

我想你可能发现了Laravel处理外键的方式的错误。它应该知道profile_types的外键是profile_type_id,但实际上它正在寻找profiletype_id

因此,您可以更改表格中的该列,这样您就不必担心每次在该表格上需要其他关系时发送额外的参数,或者在Profile模型中,您可以使用此功能像这样...

function profiletype
{
    return $this->belongsTo('ProfileType', 'profile_type_id');
}

然后您应该能够找到用户的个人资料类型...

$user = User::find(1);
echo $user->profile->profiletype->name;
echo $user->profile->profiletype->slug;
相关问题