Laravel 5.1 - 过滤关系中的一个数据

时间:2016-05-22 17:22:28

标签: php laravel eloquent laravel-5.1

我有问题要显示我的产品具有特定类别和特定性别,这是我的表格迁移和模型: 产品迁移:

[HttpGet]
        public void ExportClientsListToCSV()
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=Exported_Contacts.csv");
            Response.ContentType = "text/csv";
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());
            StringWriter sw = new StringWriter();
            sw.WriteLine("\"FullName\",\"Position\",\"BranchOffice\",\"PrivateEmail\"");
            foreach (var line in db.Persons)
            {
                sw.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"",
                                           line.FullName,
                                           line.Position,
                                           line.BranchOffice,
                                           line.PrivateEmail);
            }
            Response.Write(sw.ToString());
            Response.End();
        }

模型产品

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');
    }
}

我试图展示所有class_id = 1(T恤类别)和gender_id = 2(女性)的产品,但我有一些问题,这是我的控制器:

<?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');

    }
}

2 个答案:

答案 0 :(得分:1)

您正在从DB中提取性别模型,但不会将其用于任何用途。 试试这样:

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

答案 1 :(得分:1)

将此添加到产品型号。 使用laravel的范围

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');
}