0

Здравствуйте у меня возникла проблема.
Имеются 2 связаные таблицы users и rules.
Также есть 2 модели:
User

class User extends Authenticatable
{
    protected $table = 'users';

    protected $fillable = [
        'name', 'email', 'password', 'rule_id'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function rule()
    {
        return $this->hasOne('App\Rule', 'id');
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}    

Rule

class Rule extends Model
{
    protected $table = 'rules';

    protected $fillable = [
        'title'
    ];

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

    public static function getRules()
    {
        $rules = DB::table('rules')
            ->select('id', 'title')
            ->get();
        return $rules;
    }
}

UserController

class UserController extends Controller
{

    protected $users;

    public function __construct(User $users)
    {
        $this->users = $users;
        $this->middleware('auth');
    }

    public function index()
    {
        $users = $this->users->with(['rule' => function ($query) {
            $query->select('id', 'title');
        }])->get();
        dd($users);
    }  
}  

В таблице users имеется 3 записи но связывается только одна запись остальные идут без связи, в чем может быть проблема?

2
  • Покажите еще схему таблиц и как вы создаёте эти модели
    – xEdelweiss
    20 фев 2016 в 13:46
  • @xEdelweiss я выложил код ниже 20 фев 2016 в 16:29

2 ответа 2

1

Внешний ключ содержится в users, поэтому получается, что User принадлежит (belongsTo) к Rule. И наоборот - Rule имеет (hasOne) одного User.

Laravel предполагает, что имена ключей соответствуют названиям моделей (rule_id для Rule), поэтому указывать их не обязательно.

Получается как-то так:

class User extends Authenticatable
{
    // ...

    public function rule()
    {
        return $this->belongsTo('App\Rule');
    }

    // ...
}    

class Rule extends Model
{
    // ...

    public function user()
    {
        return $this->hasOne('App\User');
    }

    // ...
}
0
0
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('rule_id')->unsigned();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
        $table->foreign('rule_id')->references('id')->on('rules');
    });
}  

public function up()
{
    Schema::create('rules', function(Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('title', 50);
        $table->rememberToken();
        $table->timestamps();
    });
}  

Создаю через миграции

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.