iit
@iit
TeamLead + php/js разработчик

Laravel почему не работает модель один к одному?

Настраиваю модели в laravel user и profile

User::find(1)->Profile выводит

LogicException

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation


Миграция

public function up()
	{
        Schema::create('users',function($table){
            $table->increments('id');
            $table->string('email');
            $table->string('password');
            $table->string('status')->default('new');
            $table->string('status_ex')->default('new');
            $table->string('type')->default('user');
            $table->string('remember_token');
            $table->timestamps();
            $table->softDeletes();
            $table->unique('email');
            $table->index(['id','email','status','status_ex','type']);
        });
        Schema::create('profiles',function($table){
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('name');
            $table->string('family');
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
	}


Модели

class Profile extends Eloquent {

    protected $table = 'profiles';

    protected $guarded = array('id');

    protected $softDelete = true;

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


и

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

	use UserTrait, RemindableTrait;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password', 'remember_token');
    /**
     * Guarded attributes
     *
     * @var array
     */
    protected $guarded = array('id', 'password','remember_token');
    /**
     * Soft delete
     *
     * @var bool
     */
    protected $softDelete = true;
    /**
     * User profile
     */
    public function Profile(){
        return $this->hasMany('Profile');
    }


т.е через профиль можно получть пользователя а наоборот нет.
В чем может быть проблема?
  • Вопрос задан
  • 3270 просмотров
Решения вопроса 1
Для связи один к одному нужно использовать метод hasOne, а не hasMany.

Должно быть так:
/**
 * User profile
 */
public function Profile(){
    return $this->hasOne('Profile');
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы