首页 > 解决方案 > 雄辩的简单关系似乎不起作用

问题描述

我正在尝试获取与 timer_themes 关系的特定计时器,例如:

Timer::with('timer_theme')->find(1);

但它返回:

>>> Timer::with('timer_theme')->find(1);
    => App\Timer {#3245
         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",
         theme_id: 1,
         timer_theme: null,
       }

我的模型设置如下:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Timer extends Model
{
    protected $table = 'timers';

    protected $fillable = [
        'user_id',
        'slug',
        'end_time',
        'is_locked',
        'timer_theme_id'
    ];

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

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TimerTheme extends Model
{
    protected $table = 'timer_themes';

    protected $fillable = [
        'id',
        'name',
        'css_path',
        'view_path'
    ];

    public function timerThemeOptions() {
        return $this->hasMany('App\TimerOptions');
    }

    public function timer() {
        return $this->hasMany('App\Timer');
    }
}

这些是我的数据库表:

timers
-------
id
user_id
slug
end_time
is_locked
theme_id

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

我已经弄乱了模型中的关系,但仍然没有找到可行的解决方案。

标签: phplaraveleloquent

解决方案


您的关系设置正确,并按预期工作:

https://implode.io/944GOS

但是,您提供的数据库布局、代码和调试输出显示表的外键名称存在一些冲突timer_themes

确保您的timers表有一个名为 的列timer_theme_id,然后您的模型应如下所示:

<?php

namespace App;

use App\Timer;
use App\TimerOptions;
use Illuminate\Database\Eloquent\Model;

class TimerTheme extends Model
{
    protected $fillable = [
        'id',
        'name',
        'css_path',
        'view_path'
    ];

    // renamed this method for consistency
    public function timer_options()
    {
        return $this->hasMany(TimerOptions::class);
    }

    public function timer()
    {
        return $this->hasMany(Timer::class);
    }
}
<?php

namespace App;

use App\TimerTheme;
use App\Model\User;
use Illuminate\Database\Eloquent\Model;

class Timer extends Model
{
    protected $fillable = [
        'user_id',
        'slug',
        'end_time',
        'is_locked',
        'timer_theme_id'
    ];

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

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

你最好以编程方式指定类名而不是字符串,以防它们发生变化。请注意,当您使用标准命名约定时,无需为模型指定表名。(当然,它不疼。)


推荐阅读