【问题标题】:retrieve name from the other table从另一个表中检索名称
【发布时间】:2019-06-11 08:55:49
【问题描述】:

有没有使用 select 和 join 子句检索名称的有效方法?我有一个 Note、NoteType 和 NoteStatus 模型。 Note 模型中有类型和状态字段,它们将被存储为整数(代表其各自模型的 id)。 NoteType 和 NoteStatus 模型具有 id 和 name 字段。

foreach($notes as $note)
{
    $type=NoteType::where('id',$note->type)->first();
    $note->type=$type->name;
    $status=NoteStatus::where('id',$note->status)->first();
    $note->status=$status->name;
}

【问题讨论】:

  • 这些模型之间是否建立了关系?
  • @RossWilson 这些模型之间没有关系,这就是为什么考虑使用查询生成器

标签: database laravel laravel-query-builder


【解决方案1】:

模型关系

设置模型之间的关系将是最好的方法,因为您无需在每次需要调用 join 时都重新发明轮子。从长远来看,它将为您节省代码。

这里有更多信息:

Laravel Eloquent Relationships

查询生成器

如果您想手动执行此操作,则与在原始 SQL 中运行查询相同:

$note = Note::join('NoteType','Note.NoteType_id','NoteType.id')
->select('Note.*','NoteType.Name as NoteName')
->first();

现在您可以从 $note 获取所有信息

Note id = $note->id
NoteType Name = $note->NoteName

显然,请根据您的代码进行调整,但这应该有助于您积累足够的知识来解决问题。

更多信息可以在这里找到:

Laravel Query Builder Joins

【讨论】:

    【解决方案2】:

    假设您的模型名称是Note.php

    假设您的notes 表中有note_status_idnote_type_id 外键

    在你的主模型中添加关系Note.php

    public function status()
    {
        return $this->belongsTo(NoteStatus::class);
    }
    
    public function notes()
    {
        return $this->belongsTo(NoteType::class);
    }
    

    您可以检索具有类似关系的数据

    Note::with('status','notes')
         ->get()
    

    更多关于laravel关系的信息Laravel Eloquent: Relationships

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-23
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多