Laravel Eloquent 从关系中获取数据

阿尔法欧米茄

我有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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章