【发布时间】:2013-09-14 12:12:30
【问题描述】:
我正在尝试通过我的用户模型获取 ProfileType,即 $user->profile->profiletype;但是,我无法检索对象。基本上,User 有一个 Profile,而 Profile 属于 User 和 ProfileType。 ProfileType 有很多配置文件。
我的表名是 users、profiles 和 profile_types。
models/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');
}
}
models/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');
}
}
models/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');
}
}
【问题讨论】:
-
你也可以发布你的迁移吗?
-
您是否尝试过使用类似 User::with('profile.profiletype')->get(); ?
-
@user1669496 我将迁移添加到问题中。
标签: php laravel laravel-4 relationship eloquent