Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用孩子身上所拥有的东西_Php_Mysql_Laravel_Eloquent_Orm - Fatal编程技术网

Php 如何使用孩子身上所拥有的东西

Php 如何使用孩子身上所拥有的东西,php,mysql,laravel,eloquent,orm,Php,Mysql,Laravel,Eloquent,Orm,我有如下数据库关系 我想获得他们的产品的商店数据,每个产品都有自己的类别。如果我们在Laravel中使用雄辩的ORM来定义它,那么shop有许多产品属于产品类别 我可以使用获取他们的产品的商店数据,但是我无法获取每个产品的产品类别。有人知道如何获取每个产品的productCategory吗 商店模式: class Shop extends Model { public function products() { return $this->hasMany(

我有如下数据库关系

我想获得他们的产品的商店数据,每个产品都有自己的类别。如果我们在Laravel中使用雄辩的ORM来定义它,那么shop
有许多
产品
属于
产品类别

我可以使用
获取他们的产品的商店数据,但是我无法获取每个产品的产品类别。有人知道如何获取每个产品的productCategory吗

商店模式:

class Shop extends Model
{    
    public function products() {
        return $this->hasMany('App\Product');
    }
}
产品型号:

class Product extends Model
{
    public function shop() {
        return $this->belongsTo('App\Shop');
    }

    public function category() {
        return $this->belongsTo('App\ProductCategory');
    }
}
产品类别模型:

class ProductCategory extends Model
{
    public function products() {
        return $this->hasMany('App\Product');
    }
}
车间控制员获取数据:

class ShopController extends Controller
{
    public function show(Shop $shop)
    {
        $products = $shop->products()->get();
        return view('pages.shop-detail.index')->with('shop', $shop)->with('products', $products);
    }
}
关于关系:

Eloquent通过检查relationship方法的名称并在方法名称后面加上一个
\uu
,后跟主键列的名称来确定默认外键名称。但是,如果
产品
型号上的外键不是
类别id
,则应将自定义键名称作为第二个参数传递给
belongsTo
方法:

然后在视图中,在shop products上循环显示产品名称和产品类别名称:

<h3>Shop: {{ $shop->name }}</h3>
@foreach ($shop->products as $product)
    <p>Product: {{ $product->name }}</p>
    <small>Category: {{ $product->category->name }}</small>
@endforeach

请将您到目前为止所做的查询和关系的名称添加到问题中。@porloscerosψ当然,我已经添加了无法获取每个产品的productCategory的模型?我猜你是想在风景中表现出来吧?你能告诉我们怎么做吗?是的,我想在视图中显示一家商店的所有产品,但我还需要每个产品卡的产品类别@porloscerrosψ这是哪个版本的Laravel?事实上,对关系的雄辩质疑很重要。例如,如果是5.x*selectRaw,则可能是您需要走的路。好的,谢谢你。这是使用您的查询的工作,而且我已经在产品模型中添加了
产品类别\u id
,谢谢您,欢迎光临。这样做可以避免在循环视图时出现N+1问题。它会像你在问题中那样工作,但对DB来说会很紧张。我认为这个问题的答案是在关系中明确声明外键。
<h3>Shop: {{ $shop->name }}</h3>
@foreach ($shop->products as $product)
    <p>Product: {{ $product->name }}</p>
    <small>Category: {{ $product->category->name }}</small>
@endforeach
class ShopController extends Controller
{
    public function show($id)
    {
        $shop = Shop::with('products', 'products.category')->find($id);

        return view('pages.shop-detail.index')->with('shop', $shop);
    }
}