laravel - 如何根据要求按条件在 laravel eloquent 中添加或删除属性
问题描述
我有许多帖子类型的帖子模型。我需要按帖子类型控制帖子属性。例如,我有 2 种帖子类型:
- 歌曲
- 歌手
模型只发布一次。
后模型方案:
id
title
description
parent_id
type
请求song
帖子类型时,如何singer
自动将属性添加到响应数组或请求singer
帖子类型添加属性时songs
?
我在使用方法的模型内部感到厌烦__construct()
但不起作用:
public function __construct() {
if($this->type == "song") {
//$this->with = array_push($this->with, "singer");
$this->appends = array_push($this->appends, 'singer');
}
}
解决方案
public function __construct() {
parent::__construct()
if($this->type == "song") {
//$this->with = array_push($this->with, "singer");
$this->appends = array_push($this->appends, 'singer');
}
}
推荐阅读
- javascript - 如何创建交错的新闻线程?
- asp.net - 多次调用 LoggerFactory.CreateLogger<...> 会创建一个新文件吗?
- java - 正则表达式验证配置
- javascript - 更改 Ckeditor 的 textarea 的默认字体大小
- java - Android效果波纹圆圈imageView
- python - 列表中出现频率最高的数字
- matlab - Matlab中16位示波器信号的8位噪声
- c# - 从wifi转换到cable时如何检测c#上的连接被禁用?
- python - Python glob.glob():在文件名的一部分上找到完全匹配
- r - 根据名称对列进行排序 R