【发布时间】:2021-02-14 20:54:11
【问题描述】:
我需要建立动态关系,但我做不到。
表格设计如下。
页表
| id | title |
|---|---|
| 1 | Hello world |
| 2 | Contact |
分类表
| id | title |
|---|---|
| 1 | Electronics |
| 2 | Sports |
博客表
| id | title |
|---|---|
| 1 | First blog |
链接类型
| id | name |
|---|---|
| 1 | Page |
| 2 | Category |
| 3 | Blog |
链接表
| id | type_id | relation_id | slug |
|---|---|---|---|
| 1 | 1 | 1 | page/hello-world |
| 2 | 1 | 2 | page/contact |
| 3 | 2 | 1 | category/electronics |
| 3 | 2 | 2 | category/sports |
| 3 | 3 | 1 | blog/first-blog |
代码
控制器:
$links = Links::with('title')->get();
return response()->json($links);
// I need to get the "title" key.
链接模型:
public function title() {
switch($this->type_id) {
case '1':
return $this->hasOne(Page::class, 'id', 'relation_id');
break;
case '2':
return $this->hasOne(Category::class, 'id', 'relation_id');
break;
case '3':
return $this->hasOne(Blog::class, 'id', 'relation_id');
break;
}
}
此状态不起作用,因为模型尚未形成。
错误输出
Call to a member function addEagerConstraints() on null
我应该怎么做?
谢谢。
【问题讨论】:
-
刚刚注意到,但在您的
switch()中,每个案例都应返回belongsTo(Class::class, 'relation_id');而不是hasOne -
$this->type_id 总是显示为空。可能是因为尚未创建查询。
标签: laravel