Laravel如果不存在则获取大小量0 - php

我想列出所有可用产品以及每种尺寸的数量,例如

 name     | size1  | size2  | size 3 | size4   | total
 ________________________________________________________
 t-shirt1 |   0    |    1   |    3    |   9    | 13
 t-shirt2 |   3    |    1   |    1    |   9    | 14
 t-shirt3 |   0    |    0   |    0    |   0    | 0

我的Product模型与ProductSize有关系,例如:

public function sizeAvailable(){
    return $this->hasMany('App\ProductSize');

}

我的ProductSizeProduct有关系,例如:

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

我的productSizeSize有关系,例如:

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

ProductSize模型包含数量值。
因此,我能够以适当的数量获得产品的所有尺寸,而且我还能从尺寸获得所有产品。如何像我的示例一样创建列表。可以将大小用作索引吗?所以我可以做(伪代码)来填充<td>标签:

for(all products)
{
    if(product[somesize] not null)
      {{ product[somesize]->amount }}
    else
       0
}

我遇到的问题是,如果有例如1个大小(size3),而我却没有其他设置,则我不知道如何在表的<tr>中设置金额(cc)它仅包含1个值( size3),因此我需要在size1下放置0,但是如何检查size1是否不适用于该产品?
还是有更好的方法来填充表大小量?

我目前所拥有的:

 <table id="myTable" class="tablesorter table table-striped table-responsive">
        <thead>
        <tr>
            <th>
                Product
            </th>
            @foreach($sizes as $size)
                <th>
                    {{ $size->name }}
                </th>
            @endforeach
        </tr>
        </thead>
        <tbody>

            @foreach($products as $product)
                <tr >
                    <td>
                        {{ucfirst($product->name)}}
                    </td>
                    @foreach($sizes as $size)
                        <td>
                             HERE I NEED TO DO A CHECK IF $product HAS $size RETURN 0 ELSE RETURN ProductSize->amount
                        </td>
                    @endforeach



                </tr>
            @endforeach

        </tbody>
    </table>

我可以在产品模型中创建一个函数,例如:

 hasSize($size)
 {
    $result = select from ProductSize where size = $size  

    if ($result = null)
       return 0;

    return $result->amount();
 }

但是,使用这种解决方案,我必须运行一次$product->sizeAvailable()次查询,如果我有1000种产品和20种大小,那么对于一个表意味着20.000次查询。

____________________________
Relevant Database data
____________________________


products
-id           (primary key)
-name

sizes
-id           (primary key)
-name

product_sizes
-pr           (primary key)
-prodcut_id
-size_id
-amount

参考方案

您已经手动构建了一个Many to Many Relationship,Laravel已经为其提供了一些有用的功能:

1.更新产品模型(添加或替换现有关系):

public function sizes()
{
    // many to many relation with intermediate table column
    return $this->belongsToMany('App\Size', 'product_sizes')->withPivot('amount');
}

public function getTotalAttribute()
{
    // access pivot table directly and use sum aggregate
    return DB::table('product_sizes')->where('product_id', $this->attributes['id'])->sum('amount');
}

2.像这样检索模型(在控制器中):

$sizes = Size::all();
$products = Product::with('sizes')->get(); // eager load sizes

3.刀片模板:

...
<td>
    {{ucfirst($product->name)}}
</td>
@foreach($sizes as $size)
<td>
    {{-- HERE I NEED TO DO A CHECK IF $product HAS $size RETURN 0 ELSE RETURN ProductSize->amount --}}
    {{-- check and retrieve by using Collection methods --}}
    {{ $product->sizes->contains($size) ? $product->sizes->find($size)->pivot->amount : 0 }}
</td>
@endforeach
<td>{{ $product->total }}</td>
....

用上述更改和(非常小的)数据库种子重新创建示例后,我得到:

Product     size1   size2   size3   total
T-shirt1    10      3       0       13
T-shirt2    5       0       0       5

默认情况下,由于eager loading,此解决方案仅产生3个查询。 (使用DebugBar进行验证)每个total计算都会添加一个查询(不幸的是Laravel查询构建器没有数据透视表的aggregate methods)。
视图中的contains()find()遍历预取的集合-此处没有其他查询。
您不需要ProductSize模型,因为它仅包含具有附加属性(amount)的数据透视表。请参见Many to Many relationships and retrieving intermediate table columns。
为了方便起见:如果product_sizes表重命名为product_size,因此遵循Laravel的表命名约定,则不需要$this->belongsToMany('App\Size', 'product_sizes')中的第二个参数,可以这样写:$this->belongsToMany('App\Size')

[product_size]表是从相关型号名称的字母顺序得出的。

PHP PDO组按列名称查询结果 - php

以下PDO查询返回以下结果:$db = new PDO('....'); $sth = $db->prepare('SELECT ...'); 结果如下: name curso ABC stack CDE stack FGH stack IJK stack LMN overflow OPQ overflow RS…

php Singleton类实例将在多个会话中保留吗? - php

举一个简单的例子,如果我想计算一个不使用磁盘存储的脚本的命中次数,我可以使用静态类成员来执行此操作吗?用户1:<?php $test = Example::singleton(); $test->visits++; ?> 用户2:<?php $test = Example::singleton(); $test->visits+…

通过>和<运算符比较日期 - php

在我的所有php代码中,我都在UTC中存储日期和时间,但是我也在使用mysql存储日期时间(也在utc中)。大于和小于运算符会导致日期比较失败吗? $curdate=date('Y-m-d H:i:s'); if($start_datetime>$curdate) 参考方案 不。他们没有办法失败。为此,特意制作了MySQL日期格式。…

在单击时显示特定行的SQL数据 - php

我目前有2张桌子,顶部和底部。最上面的是我从SQL数据库调出的数据行。至于底部,数据来自与顶部表相同的数据库,但显示不同的字段。这些字段都在我的SQL数据库的同一行中。基本上,单击顶部表中的任何行,底部表将显示更多信息,这些信息也在SQL数据库的同一行内。我不确定如何显示特定行的数据,现在,当我单击顶部表中的任何行时,它将显示SQL中的所有行。表格代码:&l…

在Javascript或PHP中查找并替换<a>标签 - php

我正在尝试获取执行JavaScript而不是href属性的链接。我已经在网上搜寻,可以使用几种不同的方法来接近,但没有雪茄。转换示例如下所示:<a href="http://example.com">Link 1</a> <a href="http://www.yahoo.com" tar…