我正在尝试通过我的 User 模型获取 ProfileType,即 $user->profile->profiletype; 但是,我无法检索对象。基本上,User 有一个 Profile,而 Profile 属于 User 和 ProfileType。ProfileType 有很多 Profile。
我的表名是用户、配置文件和 profile_types。
模型/用户.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');
}
}