gpt4 book ai didi

database - 通过 laravel 获取数据透视表中的字段

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:42 25 4
gpt4 key购买 nike

我在 Laravel 5.5 中有一个数据透视表 M:N 关系。

基本上我的数据结构是;

Table_A
---------
id
name


Table_A_has_table_B <pivot>
---------
table_a_id
table_b_id
other_field


Table_B
---------
id
name

在我的 Table_A 模型中

public function tableb()
{
return $this->belongsToMany('App\Table_B', 'Table_A_has_table_B', 'table_a_id', 'table_b_id');
}

最后在我的 Blade View 中我有了这个

        @foreach ($tablea->tableb as $tbl)
<p><a href="#">{{ $tbl->name }}</a></p>
<p>{{ $tbl->other_field}}</p>
@endforeach

除了最后一行,所有似乎都有效

{{ $tbl->other_field}}

如何访问数据透视表中的字段和 tableb 中的数据。数据透视表包含与 tableb 相关的当前 View 的相关信息。

架构

    Schema::create('Table_A_has_table_B', function (Blueprint $table) {
$table->integer('table_a_id')->unsigned()->index();
$table->integer('table_b_id')->unsigned()->index();
$table->integer('other_field')->unsigned();
$table->primary(['table_a_id', 'competitor_id']);
$table->foreign('table_a_id')->references('id')->on('table_a')->onDelete('cascade');
$table->foreign('table_b_id')->references('id')->on('table_b')->onDelete('cascade');
});

最佳答案

你必须像这样在你的关系中添加 ->withPivot('column1', 'column2'); ( Documentation ):

public function tableb()
{
return $this->belongsToMany('App\Table_B', 'Table_A_has_table_B', 'table_a_id', 'table_b_id')->withPivot('other_field');
}

然后像这样使用 pivot 关键字:

{{ $tbl->pivot->other_field}}

关于database - 通过 laravel 获取数据透视表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47261950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com