【问题标题】:How to get column of a table (say, x) using its 'x_id' column which references the 'id' of another table in Laravel Eloquent?如何使用引用 Laravel Eloquent 中另一个表的“id”的“x_id”列获取表的列(例如 x)?
【发布时间】:2020-09-08 07:32:15
【问题描述】:

我有一个表:stage_types,包含以下列:'id'、'name'、'created_at'

另一个表:阶段,具有以下内容:'id'、'x_id'、'name'、'created_at'

说我有这个:

阶段

'id' 'stage_type_id' 'name' 'created_at'

1 1(id​​) name1 2020/00/00

2 1(id​​) name2 2020/00/00

3 2(id) name3 2020/00/00

STAGE_TYPES

'id' 'name' 'created_at'

2020/00/00 1 件事

2 2020/00/00

3 2020/00/00

在 stage 表中,“stage_type_id”列是使用以下方法创建的:

        $table->unsignedBigInteger('stage_type_id');
        $table->foreign('stage_type_id')->references('id')->on('stage_types');

我如何在控制器中START WITH STAGES TABLE 即 DB::table('stages')..... 并参考 name使用“stage_type_id”列的阶段类型?

模型关系:

  • 一个阶段属于一个阶段类型
  • StageType 有一个阶段

(这可能是错误的做法)

【问题讨论】:

    标签: database laravel model-view-controller eloquent schema


    【解决方案1】:

    不太清楚您要达到的目标以及为什么要使用DB 外观。

    如果如你所说:

    一个阶段属于一个阶段类型

    然后您将使用定义关系的函数名称来引用阶段类型:

    假设你有,在阶段模型中:

    public function types()
    {
        return $this->belongsTo(StageType::class);
    }
    
    

    您可以参考 Stages 类型,例如:

    $stage = App\Stage::first();
    $nameOfStageType = $stage->types->name;
    

    【讨论】:

      【解决方案2】:

      此连接用于两个表。 在 SQL('SELECT * FROM stages JOIN stage_type on stages.id = stage_type.stage_id ')

      $joinedTables = App\Stage::join('stage_type','stages.id','=','stage_type.stage_id')->get();

      【讨论】:

      • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
      猜你喜欢
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      相关资源
      最近更新 更多