代码之家  ›  专栏  ›  技术社区  ›  Rey Young

laravel-elokent:当没有数据时,elokent关系需要返回一些东西,而不是返回null对象

  •  2
  • Rey Young  · 技术社区  · 8 年前

    我的产品型号上有这种关系。

    public function productInventory(){
            return $this->hasOne('App\Models\Ecommerce\Inventory', 'product_id')->where('is_deleted', 0);
    }
    

    有时,我可能没有在库存表中插入特定的产品。因此,此关系仍在视图中,但将尝试获取productInventory->会引发错误的价格, . 所以,我现在做了这个,这只是一件简单的事情。但计数是1或大于1,因为还有其他产品。那么,对于库存表中没有数据的特定产品,我如何才能只返回null呢?

    public function productInventory(){
            $has_inv = Inventory::where('product_id',$this->id)->where('is_deleted', 0)->count();        
            if($has_inv < 1){
                return null;
            }
            return $this->hasOne('App\Models\Ecommerce\Inventory', 'product_id')->where('is_deleted', 0);
        }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   redcenter    8 年前

    首先,方法productInventory()必须返回关系。对于某些记录,没有关联的清单并不重要。这个方法必须返回关系,仅此而已。。。把这个退货和数据库的实际状态混为一谈(“对于这个特定的产品,没有存货”),是一个真正的不可能,IMHO。

    检查视图中是否有可用的对象,然后才检查该对象的price属性。

    你可以用这样的方法来检查。。。

    @if(is_null($productInventory)) 
     {{$productInventory->price}}
    @endif
    

    顺便说一句,这是一个例子的代码,而不是实际的代码。但它给了你解决这个问题的方法。

    如果在很多视图中都使用此功能,则必须优化视图结构(通过使用includes!),不要带着问题移动到代码中的不同位置。

    为经常使用的视图代码创建一个include,include是这样的:

    @include('product_incventory_price_data')
    

    关于刀片中的包含

    <head> 在网页中输入代码。您可以将其添加到所有单独的网页(视图文件)。让我们看两个不同的视图(A en B)

    文件:view\ a.blade.php

    <html>
    <head>
        <meta charset="utf-8">
        <title>{{$page->title}}</title>
        <meta name="description" content="{{$page->description}}">
        <meta name="keywords" content="{{$page->keywords}}">
    </head>
    <body>
    ...stuff for view A
    </body>
    </html>
    

    文件:view\ b.blade.php

    <html>
    <head>
        <meta charset="utf-8">
        <title>{{$page->title}}</title>
        <meta name="description" content="{{$page->description}}">
        <meta name="keywords" content="{{$page->keywords}}">
    </head>
    <body>
    ...stuff for view B
    </body>
    </html>
    

    更好的解决方案:全部移动 <头部>

    共享/head.blade.php

    <head>
        <meta charset="utf-8">
        <title>{{$page->title}}</title>
        <meta name="description" content="{{$page->description}}">
        <meta name="keywords" content="{{$page->keywords}}">
    </head>
    

    视图a

    <html>
    @include('shared/head')
    <body>
    ...stuff for view A
    </body>
    </html>
    

    视图\u b

    <html>
    @include('shared/head')
    <body>
    ...stuff for view B
    </body>
    </html>
    

    您可以使用各种视图代码来实现这一点。此外,您的产品价格信息可以移动到一个地方,并使用@include()在多个其他视图中使用。。。

    控制器传递给视图的数据也传递给include文件。别担心……:-)

    Laravel documentation about views & sub-views

    推荐文章