gpt4 book ai didi

php - Laravel 5.1 - 查看具有关系的数据过滤器

转载 作者:行者123 更新时间:2023-11-29 01:37:21 25 4
gpt4 key购买 nike

我在显示具有特定类别的产品时遇到问题,这是我的表迁移和模型:产品迁移:

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->timestamps();

模型产品

<?php

namespace dixard;

use Illuminate\Database\Eloquent\Model;

use dixard\User;

use dixard\Category;

use dixard\OrderItem;

use dixard\Color;

class Product extends Model
{

protected $table = 'products';

protected $fillable =

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

];



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


}

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

}

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

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

模型类别

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

}

}

我正在尝试显示 category_id = 1 的所有产品,此类别 id=1 是我的 T 恤类别。我的 Controller :

use dixard\Product;
use dixard\Category;

class TshirtController extends Controller
{

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

dd($product_man) OR
return view('store.shop.men',compact('product_men'));

// It doesnt work, doesnt show me nothing.

}

最佳答案

试试这个:

Category::find(catagory_id)->products;

示例:

Category::find(1)->products;

您还可以使用where 子句:

例子:

Category::where('name', 't-shirt')->products;

引用:https://laravel.com/docs/5.1/eloquent-relationships

关于php - Laravel 5.1 - 查看具有关系的数据过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37361497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com