我有Task
模型。我的Task
模型有一些关系,目前看起来像这样:
class Task extends Model
{
use HasFactory;
public $timestamps = false;
public function city()
{
return $this->hasOne(City::class, 'id', 'city_id');
}
public function type()
{
return $this->hasOne(Type::class, 'id', 'type_id');
}
public function note()
{
return $this->hasOne(Note::class, 'id', 'note_id');
}
public function operator()
{
return $this->hasOne(User::class, 'id', 'operator_id');
}
}
现在,TasksController
我需要获取符合特定条件的任务,如下所示:
$tasks = Task::whereCityId($city->id)->whereTypeId($type->id)->get()->toArray();
问题是命名的字段city_id
type_id
note_id
operator_id
将获得我的integer
值。
相反,我想从相关模型中获得某些价值。
例如:
operator_id
应替换为username
对应于用户 ID 的用户表。
一个明显的解决方案是简单地使用foreach
循环,查看我的结果并获取我需要的数据,然后简单地创建另一个替换信息的数组,但我不确定这是否是最好的主意,也许还有更好的主意。
您必须更改代码:
$this->hasOne(ClassName::class, 'id', 'foreign_key');
至
$this->belongsTo(ClassName::class, 'foreign_key', 'id');
因为 Task 的 id 在这些表中不能用作外键。这些表的 id 作为外键出现在任务表中,因此您必须使用belongsTo()关系来告诉脚本这些 id 所属的位置。
然后访问这样的属性:
$tasks = Task::with("type", "city", "operator")
->whereCityId($city->id)->whereTypeId($type->id)->get();
foreach($tasks as $task){
echo $task->city->name;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句