【问题标题】:Laravel 5.1 - Filter more one data with relationshipLaravel 5.1 - 过滤更多具有关系的数据
【发布时间】:2016-09-19 12:40:06
【问题描述】:

我无法展示具有特定类别和特定性别的产品,这是我的表格迁移和模型: 产品迁移:

Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 255);
            $table->string('slug'); 
            $table->text('description');
            $table->string('extract', 300);
            $table->decimal('price', 5, 2);
            $table->string('image', 300);
            $table->boolean('visible');
            $table->integer('user_id')->unsigned();

            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade');

            $table->integer('category_id')->unsigned();

            // relations  
            $table->foreign('category_id')
                  ->references('id')
                  ->on('categories')
                  ->onDelete('cascade');
            $table->integer('gender_id')->unsigned();


            $table->foreign('gender_id')
              ->references('id')
              ->on('genders')
              ->onDelete('cascade');

            $table->timestamps();

模型产品

<?php

namespace dixard;

use Illuminate\Database\Eloquent\Model;

use dixard\User;

use dixard\Category;

use dixard\Gender;

use dixard\OrderItem;

use dixard\Color;

class Product extends Model
{

    protected $table = 'products';

    protected $fillable = 

    [
    'name',
    'slug',
    'description',
    'extract',
    'image',
    'visible',
    'price',
    'category_id',
    'gender_id',
    'user_id'

    ];



    public function user() {
            return $this->belongsTo('dixard\User');


    }

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

    }

    public function gender() {
        return $this->belongsTo('dixard\Gender');
    }



    public function OrderItem() {
            return $this->belongsTo('dixard\OrderItem');

    }


    public function Color() {
            return $this->belongsTo('dixard\Color');

    }

}

类别迁移

Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 255)->unique();

            $table->string('slug');
            $table->text('description');

            $table->string('color', 30);


        });

型号类别

use dixard\Product;

class Category extends Model
{
    protected $table = 'categories';

    protected $fillable = [

    'name',
    'slug',
    'description',
    'color',


    ];
    public $timestamps = false;

    public function products() {

        return $this->hasMany('dixard\Product');

    }

}

性别迁移

<?php

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

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

            $table->text('gender');


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

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

性别模型

<?php

namespace dixard;

use Illuminate\Database\Eloquent\Model;

use dixard\Product;

class Gender extends Model
{
    protected $table = 'genders';


    // gli dico che voglio scrivere questo campi
    protected $fillable = [

    'gender',


    ];
    public $timestamps = false;

    public function products() {

        return $this->hasMany('dixard\Product');

    }
}

我正在尝试显示所有具有 category_id = 1(T 恤类别)和 gender_id = 2(女性性别)的产品,但我有一些问题,这是我的控制器:

use dixard\Product;
use dixard\Category;
use dixard\Gender;

class TshirtController extends Controller
{

       public function men_tshirt()
        { 
            $category = Category::where('name', '=', 't-shirt')->orderBy('id', 'desc')->first();
            $gender = Gender::where('gender', '=', 'woman')->orderBy('id', 'desc')->first();

            $products = $category->products();
            return view('store.shop.woman',compact('products'));

            // It filter only category and not gender woman

        }

【问题讨论】:

  • 男装女装 T 恤?确定?

标签: php laravel eloquent laravel-5.1


【解决方案1】:

您正在从 DB 中提取 Gender 模型,但没有将其用于任何用途。 试试这样:

        $products = $category->products()->where(['gender_id' => $gender->id])->get();

【讨论】:

  • 非常感谢!是的,它确实有效,你认为这是从我的表中过滤关系的最佳方法吗?谢谢你的帮助!
  • 我从 Laravel 学到的一件事是,有十几种方法可以做任何事情,但没有一种方法是“最好的”或“正确的”方法。您可以将整个事情作为一个链接的单行查询来完成,或者您可以做一堆简单的查询。做任何适合你的事情。
【解决方案2】:

将此添加到产品模型。 使用 laravel 的 scope

product.php

public function scopeCategory($query, Category $category)
{
    if($category) {
        return $query->whereCategoryId($category->id);
    }
    return $query;
}

public function scopeGender($query, Gender $gender)
{
    if($gender){
        return $query->whereGenderId($gender->id);
    }
    return $query;
}

TshirtController

public function men_tshirt()
{
    $category = Category::whereName('t-shirt')->orderBy('id', 'desc')->first();
    $gender = Gender::whereGender('woman')->orderBy('id', 'desc')->first();

    $products = Product::category($category)->gender($gender)->get()->toArray();

    return view('store.shop.men',compact('products'));
}

另外如果您想处理反向关系,您可能需要将以下内容添加到 Product.php

public function categories()
{
    return $this->belongsTo('dixard\Category.php');
}

public function gender()
{
    return $this->belongsTo('dixard\Gender.php');
}

【讨论】:

  • 我收到此错误:TshirtController.php 第 33 行中的 ErrorException:不应静态调用非静态方法 dixard\Product::category(),假设 $this 来自不兼容的上下文,我已更正- > $products = 带有产品的产品。
  • @Diego182 哎呀..它应该是 Product:: not Products:: 错字
猜你喜欢
  • 2016-09-18
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 2021-08-07
  • 2018-05-20
  • 1970-01-01
  • 2019-07-24
  • 2020-12-18
相关资源
最近更新 更多