php - Laravel:我如何从这个数据透视表中获取数据?

标签 php laravel laravel-5 pivot-table laravel-5.3

已解决:下面发布了答案

如何从此数据透视表和规范表中获取值?

我想在这样的模板中显示它:

-型号(规范表中的名称)

--品牌(属性形式数据透视表):example1(数据透视表中的值)

--模型(属性形式透视表):example123(来自透视表的值) ...


在 ProductController 中,我尝试返回类似这样的内容 $product = Product::with('specifications')->first();,但是我只能从规范表中获取数据尝试 $product = Product::with('product_specification')->first(); 我收到错误消息 Call to undefined relationship [product_specification] on model [App\Product].


数据透视表:

public function up()
{
    Schema::create('product_specification', function (Blueprint $table) {
        $table->engine = 'InnoDB';

        $table->increments('id');
        $table->integer('product_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->integer('specification_id')->unsigned()->index();
        $table->foreign('specification_id')->references('id')->on('specifications')->onDelete('cascade');
        $table->string('attribute');
        $table->string('value');
    });
}

规范表:

public function up()
{
    Schema::create('specifications', function (Blueprint $table) {
        $table->engine = 'InnoDB';

        $table->increments('id');
        $table->string('name')->unique();
        $table->timestamps();
    });
}

产品型号:

public function specifications() 
{
    return $this->belongsToMany(Specification::class, 'product_specification');
}

最佳答案

我必须将 withPivot() 添加到我的 Product 模型中

public function specifications() {
    return $this->belongsToMany(Specification::class, 'product_specification')->withPivot('attribute', 'value');
}

然后在模板中:

foreach($product->specifications as $specification) {
    echo 'name: ' . $specification->name . ' attribute: ' . $specification->pivot->attribute . ' value ' . $specification->pivot->value . '</br>';
}

关于php - Laravel:我如何从这个数据透视表中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304921/

相关文章:

html - 在 HTMTL::link_to_route() 中使用 html 标签

Laravel:webhooks 需要绕过 Laravel 的 CSRF 验证

php - 获取另一行 GROUP BY 行的 SUM

php - Yii Framework 如何从数据库中获取所有表名和列名

php - Laravel 5.1 服务容器 : Binding using something other than the class name?

php - Composer : Updating a Project Created with `create-project`

php - laravel 5 从未找到的数据库类中获取数据

PHP IP 地址在循环中被截断

php - 使用 jQuery 按 <td> 过滤表中的 mySQL 查询结果?

php - 可以在 PHP 图像渲染脚本上执行 javascript 吗?