Laravel Красноречивая связь с двумя уникальными индексами - PullRequest
0 голосов
/ 26 марта 2020

Я создаю приложение таймера, в котором пользователь может обновить тему, и у меня возникают проблемы с настройкой отношений, в которых правильно указаны два уникальных ключа, так как я новичок в Eloquent и Laravel.

База данных:

timers
-------
id
user_id
slug
is_locked
timer_theme_id

timer_themes
-----------
id
name
view_path
css_path

timer_theme_options
-----------------
id
timer_theme_id
name
type
selector
attributes
default_value

user_timer_options
----------------
id
timer_theme_options_id
user_id
value

У меня все работает, кроме получения правильного пользователя, указанного user_timer_options.

например, следующий вывод на php ремесленник тинкер:

>>> Timer::find(1)->with('timer_theme.timer_theme_options.user_timer_option')->get();
=> Illuminate\Database\Eloquent\Collection {#3296
     all: [
       App\Timer {#3286
         id: 1,
         user_id: 1,
         slug: "test",
         end_time: "2020-03-25 21:59:14",
         is_locked: 1,
         created_at: "2020-03-24 18:26:33",
         updated_at: "2020-03-25 19:59:14",
         timer_theme_id: 1,
         timer_theme: App\TimerTheme {#3272
           id: 1,
           name: "Default",
           view_path: "timers.display_timer",
           css_path: "css/timer_themes/default.css",
           created_at: null,
           updated_at: null,
           timer_theme_options: Illuminate\Database\Eloquent\Collection {#3295
             all: [
               App\TimerThemeOptions {#3304
                 id: 1,
                 timer_theme_id: 1,
                 name: "Outer Ring Color",
                 type: "1",
                 selector: ".timer.hour .hand span",
                 default_value: "238062061045",
                 created_at: null,
                 updated_at: null,
                 attributes: "border-top-color, border-right-color",
                 user_timer_option: App\UserTimerOptions {#3317
                   id: 1,
                   timer_theme_options_id: 1,
                   user_id: 3,
                   value: "111222333100",
                   created_at: null,
                   updated_at: null,
                 },
               },
               App\TimerThemeOptions {#3310
                 id: 2,
                 timer_theme_id: 1,
                 name: "Inner Ring Color",
                 type: "1",
                 selector: ".timer.minute .hand span",
                 default_value: "065064066040",
                 created_at: null,
                 updated_at: null,
                 attributes: "border-top-color, border-right-color",
                 user_timer_option: null,
               },
             ],
           },
         },
       },
     ],
   }

он выбирает только первый параметр, который относится к timer_theme_options_id, и не заботится о пользователе. Посмотрев документацию, я не совсем уверен, как добавить это в модель, так как модель timer_theme_options не содержит user_id.

вот мои модели:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TimerThemeOptions extends Model
{

    protected $fillable = [
        'id',
        'timer_theme_id',
        'type',
        'name',
        'selector',
        'attributes',
        'default_value'
    ];

    public function user_timer_option() {
        //has one through? - user_id and timer_theme_options_id
        return $this->hasOne(UserTimerOptions::class);
    }

    public function timer_theme() {
        return $this->belongsTo(TimerTheme::class);
    }
}

и

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserTimerOptions extends Model
{

    protected $fillable = [
        'id',
        'timer_theme_options_id',
        'user_id',
        'value'
    ];

    public function timer_theme_option() {
        return $this->belongsTo(TimerThemeOptions::class);
    }

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

}

, наконец, база данных user_timer_options настроена с уникальными индексами:

<?php

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

class CreateUserTimerOptionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_timer_options', function (Blueprint $table) {
            $table->id();
            $table->integer('timer_theme_options_id');
            $table->integer('user_id');
            $table->string('value');
            $table->timestamps();
            $table->unique(['user_id', 'timer_theme_options_id']);
        });
    }

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