雄辩的热切加载并不符合我的命名惯例

时间:2016-03-03 17:25:01

标签: php laravel-5 eloquent

当我在Laravel的控制器中请求产品的同时,我一直渴望加载产品图像,我大部分时间都被困住了。

public function ProductImages() {
        return $this->hasMany('App\ProductImage', 'product_id'); // this matches the Eloquent model
  }

我更改了代码以进行FK'测试'突然它开始返回我想要的相应数据。我把FK放回到product_id但又回到了一个空数组。下面是我的产品模型ProductImages模型以及在控制器中进行调用的两者的迁移

产品型号

class Product extends Model
{
 protected $fillable = array('name', 'url_name', 'sku', 'description', 'short_description', 'enabled', 'track_inventory', 'stock_level', 'allow_backorder', 'updated_user_id' );

//protected $hidden = array('id');


// LINK THIS MODEL TO OUR DATABASE TABLE ---------------------------------
// Database table is not called my_products
protected $table = 'products';

// each  product HAS many product images
public function ProductImages() {
    return $this->hasMany('App\ProductImage', 'productId'); // this matches the Eloquent model
}
}

产品图片型号

class ProductImage extends Model
{
 protected $fillable = array('name', 'description', 'path', 'sort_order', 'product_id');
// DEFINE RELATIONSHIPS --------------------------------------------------
// each attribute HAS one product
public function Product() {
    return $this->belongsTo('App\Product', 'id'); // this matches the Eloquent model
}
}

产品迁移

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('url');
            $table->string('sku');
            $table->string('description');
            $table->string('short_description');
            $table->integer('enabled');
            $table->integer('track_inventory');
            $table->integer('stock_level');
            $table->integer('allow_backorder');
            $table->dateTime('updated_user_id');



            $table->timestamps();
        });
    }
}

产品图片迁移

class CreateProductImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('product_images', function (Blueprint $table) {
            $table->increments('id');


            $table->string('name');
            $table->string('description');
            $table->string('path');
            $table->integer('sort_order');
            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('products');

            $table->timestamps();
        });
    }
}

产品控制器代码段

 public function index()
    {
        //
        $Products = Product::with('ProductImages','productTypes')->get();

        //dd($Products);

        return response()->json( $Products, 200);

    }

如果你能帮助我理解为什么会发生这种奇怪的行为,我将非常感激。

0 个答案:

没有答案
相关问题