通过 laravel 在 Pivot table 上获取字段
Getting fields on Pivot table through laravel
我在 Laravel 5.5.
中有一个 Pivot table 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 观点中我得到了这个
@foreach ($tablea->tableb as $tbl)
<p><a href="#">{{ $tbl->name }}</a></p>
<p>{{ $tbl->other_field}}</p>
@endforeach
除了最后一行之外,所有似乎都有效
{{ $tbl->other_field}}
如何访问数据透视表 table 上的字段和 tableb
上的数据。
数据透视 table 包含与 tableb
.
相关的当前视图的相关信息
架构
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}}
我在 Laravel 5.5.
中有一个 Pivot table 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 观点中我得到了这个
@foreach ($tablea->tableb as $tbl)
<p><a href="#">{{ $tbl->name }}</a></p>
<p>{{ $tbl->other_field}}</p>
@endforeach
除了最后一行之外,所有似乎都有效
{{ $tbl->other_field}}
如何访问数据透视表 table 上的字段和 tableb
上的数据。
数据透视 table 包含与 tableb
.
架构
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}}