在laravel中显示一对一关系的结果

时间:2017-11-29 15:12:41

标签: laravel eloquent

我有一对一的关系给了我所需的结果,但我无法在我看来显示结果。

这是我的控制器功能

        public function showallProducts()
{    // parent table
    $productstock = Product::with('CurrentPrice')->get();
    return view('welcome', compact('productstock'));
}

我的观点

  <table>
            <tr>
                <th>id</th>
                <th>name</th>
                <th>description</th>
                <th>price</th>
            </tr>
            @foreach ($productstock as $value)
                <tr>
                    <td>

                        {{--<h4><a href="{{url('Job-Details',$show->id)}}">
              {{$show->jobTitle}}</a></h4>--}}

                        <p>{{ $value->id }}</p>
                    </td>
                    <td>
                        <i class="fa fa-map-marker"></i>
                        <P>{{ $value->name }}</P>
                    </td>
                    <td><span>{{ $value->description }}</span>
                    </td>

                    <td><span>{{ $productstock->CurrentPrice->productprice 
           }}</span>
                    </td>

                </tr>

            @endforeach
        </table>

它给我以下错误

 Property [CurrentPrice] does not exist on this collection instance

当我在控制器中执行dd()时,我得到以下结果。

       Array
       (
             [0] => Array
       (
        [id] => 1
        [name] => effertz.org
        [description] => Williamson, Kozey and Marks
        [created_at] => 2017-11-28 14:01:19
        [updated_at] => 2017-11-28 14:01:19
        [current_price] => Array
            (
                [id] => 5
                [product_id] => 1
                [productprice] => 52
                [created_at] => 2017-11-28 14:01:21
                [updated_at] => 2017-11-28 14:01:21
            )

        )

         [1] => Array
          (
        [id] => 2
        [name] => gulgowski.biz
        [description] => Schaefer, Simonis and Kiehn
        [created_at] => 2017-11-28 14:01:19
        [updated_at] => 2017-11-28 14:01:19
        [current_price] => Array
            (
                [id] => 6
                [product_id] => 2
                [productprice] => 99
                [created_at] => 2017-11-28 14:01:21
                [updated_at] => 2017-11-28 14:01:21
            )

    )

我如何在视图中显示结果以及上述错误的原因是什么似乎很好

1 个答案:

答案 0 :(得分:1)

您正在使用循环进行循环:foreach ($productstock as $value)

因此,在您看来,您应该使用$value而不是整个集合$productstock。 更改您的观点:{{ $productstock->CurrentPrice->productprice }}{{ $value->CurrentPrice->productprice }}