php - 雄辩的简单关系似乎不起作用
问题描述
我正在尝试获取与 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
我已经弄乱了模型中的关系,但仍然没有找到可行的解决方案。
解决方案
您的关系设置正确,并按预期工作:
但是,您提供的数据库布局、代码和调试输出显示表的外键名称存在一些冲突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);
}
}
你最好以编程方式指定类名而不是字符串,以防它们发生变化。请注意,当您使用标准命名约定时,无需为模型指定表名。(当然,它不疼。)
推荐阅读
- coq - 从库中查找函数
- php - 如何通过复合主键从两个表中选择一个?
- php - Cpanel php 版本!= .htaccess 文件
- javascript - 如何处理 JavaScript 中的事件?
- javascript - 如何为类的每个实例设置不同的间隔值
- python - QtDesigner 将字体大小设置为 -1
- reactjs - 根据环境(产品或测试)动态更改我使用的云功能
- python - 在具有透明度的 3D 图像上叠加 2D 热图
- c# - 使用 CreatedAtAction 从 Web API 控制器返回自创建的 JSON 而不转义?
- git - 错误:.git/logs/HEAD [冲突] 的错误参考