laravel - 将关系数据直接附加到模型
问题描述
文章模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Articles extends Model
{
protected $table = 'articles';
protected $primaryKey = 'idArticle';
protected $fillable = [
'idArticle', 'Topic', 'Image', 'Content', 'Views',
];
protected $hidden = [
'idCategory', 'idUser',
];
public function category()
{
return $this->hasOne(Categories::class, 'idCategory', 'idCategory');
}
}
所以现在当我打电话时$article = Articles::find(1);
,它会从文章表中返回数据,当我添加时$article->category;
,它会添加数据$article->category->Name
。我想Name
直接在里面$article
- 像$article->category
(所以$article->category->Name
进入$article->category
)是否可以仅使用模型类来定义它,或者我需要将它映射到控制器中?
解决方案
您可以将自定义属性分配给您的模型类。但是你不能使用与你的category()
方法相同的属性名,因为它已经被$article->category
.
一个例子给你一个名为category_name
class Articles extends Model
{
// attributes to append to JSON responses
protected $appends = ['category_name'];
// ... your other properties and methods
// your custom attribute
public function getCategoryNameAttribute()
{
if (!is_null($this->category)) {
return $this->category->Name;
}
return '';
}
}
用于:
$article->category_name
推荐阅读
- java - 为什么在 JVM 检测到运行时异常时无法防止死锁?
- python - 打开 TKinter 窗口会暂停程序的其余部分
- python - 在 Azure 上使用 HTML 触发器运行网页抓取 Python 文件
- parsing - 使用单声道在 F# 中生成解析器的命令行
- javascript - 在反应输入字段中渲染所有世界大学 - 堆栈大小超出错误
- nginx - Nginx 入口控制器 - 基于路径的路由
- react-native - 如何在抽屉导航中放置一些文本反应原生
- python - 为什么我不能将 .py 文件导入同一目录中的另一个文件?
- kubernetes - 如何强制 kubernetes gitlab-runner 使用宿主网络?
- python - TensorFlow 1.7 + Keras 和数据集:对象没有属性“ndim”