我正在尝试获取与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);
}
}
最好以编程方式而不是字符串形式指定类名称,以防它们更改。请注意,按原样使用标准命名约定时,不必为模型指定表名。(当然,它没有伤害。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句