拥有许多与pikey键的关系返回null

时间:2019-09-04 10:57:07

标签: php laravel laravel-5 primary-key relation

在我的应用中,我希望在附件和产品之间建立一种关系,其中一个产品可以包含许多附件,

我创建了一个addons tableproduct tableaddon_product表来保存ids

已经定义了模型中的关系,甚至可以创建模型addonsProducts并将键插入我的controller

我希望在我致电产品时在我的Api resources响应中显示这些插件。

插件模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Addon extends Model
{
    protected $fillable = ['name','price', 'icon', 'description'];
    protected $table = 'addon_products';

      public function products()
     {
       return $this->belongsToMany(Product::class);
     }
}

插件迁移

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Addons extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('addons', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('price');
            $table->string('icon');
            $table->string('description');
            $table->timestamps();
        });    
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('addons');
    }
}

产品型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{

  protected $fillable = ['name','brand', 'type', 'icon', 'price', 'description'];
// protected $table = 'products';

  public function stores()
 {
   return $this->belongsToMany(Store::class);
 }
  public function orders()
  {
    return $this->belongsToMany(Order::class);
  }
  public function addons()
    {
      return $this->hasMany(Addon::class);
    }

}

产品迁移

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('icon');
            $table->string('brand');
            $table->string('type');
            $table->string('price');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

附加产品型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AddonProducts extends Model
{
    protected $fillable = ['addon_id','product_ids', 'active'];
    //protected $table = 'addon_product';

      public function products()
     {
       return $this->belongsToMany(Product::class);
     }
     public function addons()
     {
      return $this->hasMany(Product::class);
    }
}

附加产品迁移

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddonProduct extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('addon_product', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('addon_id')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->integer('active')->unsigned();
            $table->timestamps();
        });    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('addon_product');
    }
}

产品资源

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
      return [
     'id' => $this->id,
     'productname' => $this->productname,
     'icon' => $this->icon,
     'brand' => $this->brand,
     'type' => $this->type,
     'price' => $this->price,
     'addons' => $this->addon,
     'created_at' => (string) $this->created_at,
     'updated_at' => (string) $this->updated_at,

   ];
    }
}

附加资源

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class AddonResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'price' => $this->price,
            'icon' => $this->icon,
          ];
    }
}

1 个答案:

答案 0 :(得分:2)

无需在类Addon中声明表,也无需正确声明表并添加枢纽字段active

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Addon extends Model
{
    protected $fillable = ['name','price', 'icon', 'description'];
    protected $table = 'addons';

      public function products()
     {
       return $this->belongsToMany(Product::class)->withPivot('active');
     }
}

Product类中,也将该关系声明为belongsToMany

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name','brand', 'type', 'icon', 'price', 'description'];

    public function stores()
    {
        return $this->belongsToMany(Store::class);
    }

    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

    public function addons()
    {
        return $this->belongsToMany(Addon::class)->withPivot('active');
    }
}

您无需声明类AddonProduct,因为它表示一个联系表。

现在您可以轻松做到:

$products = Product::with('addons')->get();

您还可以在active字段上运行条件。

$products = Product::with(['addons' => function($addon) {
    $addon->where('pivot.active', '=', 1);
}->get();