如何在laravel

时间:2016-02-01 10:32:49

标签: php laravel-5 laravel-5.1

我正在尝试使用雄辩的模型建立一对多关系,并希望在指定的类别中显示产品 那是我的产品型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\softDeletes;

class Product extends Model
{
    use softDeletes;
    protected $table='products';

    public function category(){
        return $this->belongsTo('App\Category');
    }
}

这是我的分类模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\softDeletes;

class Category extends Model
{
    use softDeletes;
    protected $table='category';

   public function product(){
    return $this->hasMany('App\Product','category_id','id');
   }
}

这就是产品控制者:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Product;
use App\Category;

class productsController extends Controller
{
    public function getShow($id,Request $request){
            $in=$request->get('id');
            $category=Category::all();
            $product=Product::find($id);
            $products=$product->category()->where('category_id','=',$in);

            return view ('contents.products')->with('products',$products)
                                            ->with('category',$category);
    }
}

这是产品表:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('category_id');
        $table->string('describtion');
        $table->string('image_name');
        $table->timestamps();
        $table->softDeletes();
    });
}

这就是类别表:

public function up()
{
    Schema::create('category', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
        $table->softDeletes();
    });
}

它给了我这个错误:在非对象上调用成员函数category()

那我怎么解决呢?

1 个答案:

答案 0 :(得分:0)

据我所知,你的问题是:

在您的控制器中:

$category = Category::find($id);
$products = $category->product;

更好的是,您可以使用急切加载而忘记手动分配产品:

控制器:

$category = Category::with('product')->where('id', 1)->first();

希望这对你有所帮助。