2 回答
TA贡献1813条经验 获得超2个赞
我想知道是否需要attribute_record 表的模型。
不,这是一个数据透视表,当你正确设置关系时,Laravel 会透明地使用它。我假设这是一个多对多的关系(记录可以有很多属性,很多记录可以有相同的属性)所以定义你的关系,剩下的由 Laravel 完成:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Attribute extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
public function records()
{
return $this->belongsToMany('\\App\\Record')
->withPivot('value')
->withTimestamps();
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Record extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
public function attributes()
{
return $this->belongsToMany('\\App\\Attributes')
->withPivot('value')
->withTimestamps();
}
}
现在在控制器中你可以这样做:
$record = \App\Record::find($id);
foreach ($record->attributes as $attribute) {
// $attribute is an instance of \App\Attribute
// to access the values in the pivot table, use the pivot attribute
echo $attribute->pivot->value;
}
TA贡献1815条经验 获得超13个赞
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Record extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
public function attributes()
{
return $this->belongsToMany(Attribute::class, 'attribute_record')
->withPivot('value');
}
}
然后你可以访问这样的值:
foreach($record->attributes as $attribute) {
echo $attribute->pivot->value;
}
当您使用withPivot方法指定值时,您可以在 下访问它们$relatedInstance->pivot->yourColumn。
枢轴值是从中间关系表中检索的(attribute_record在您的示例中)
- 2 回答
- 0 关注
- 161 浏览
添加回答
举报