微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-Laravel 5.1-Foreach数据形式(Blade)

我有一个问题,无法显示我的产品的颜色,我试图用刀片foreach来显示它们,但是它不起作用.
我的资源控制器:

public function show($id){
        $colors = Color::where('product_id', $id)->orderBy('id', 'asc');
        $product = Product::where('id', $id)->first();

        return view('store.show', compact('product','colors'));     
    }

这是我的桌子颜色,我正确添加了关系

enter image description here


产品型号:

namespace dixard;

use Illuminate\Database\Eloquent\Model;
use dixard\User;
use dixard\Category;
use dixard\Gender;
use dixard\OrderItem;
use dixard\Color;

class Product extends Model
{
    protected $table = 'products';
    protected $fillable = 
    [
        'name',
        'slug',
        'description',
        'extract',
        'image',
        'visible',
        'price',
        'category_id',
        'gender_id',
        'user_id'
    ];

    // Colleghiamo OGNI prodotto ha un utente
    public function user() {
        return $this->belongsTo('dixard\User');
    }

    // Colleghiamo OGNI prodotto ha una categoria
    public function category() {
        return $this->belongsTo('dixard\Category');
    }

    public function gender() {
        return $this->belongsTo('dixard\Gender');
    }

    // prodotto è contenuto in TANTI order item
    public function OrderItem() {
        return $this->belongsTo('dixard\OrderItem');
    }

    // prodotto è contenuto in TANTI order item
    public function Color() {
        return $this->belongsTo('dixard\Color');
    }
}

颜色模型

namespace dixard;

use Illuminate\Database\Eloquent\Model;

class Color extends Model
{
    protected $table = 'colors';

    // gli dico che voglio scrivere questo campi
    protected $fillable = [
        'color',
        'product_id',
    ];

    public $timestamps = false;

    // Ogni color HA tanti prodotti. // Ogni prodotto ha tanti colori
    public function products() {
        return $this->hasMany('dixard\Product');
    }
}

我正在尝试显示我的产品可用的颜色,因此:

<label for="p_color">Color</label>
@foreach($colors as $color)
    <td>{{ $color->color }}</td>
@endforeach

这只是测试!我想显示一个选择选项,我尝试使用BLADE,但是它不起作用,

>获得所有颜色,其中product_id = $id可以正常工作.
>获得id = $id的产品正常工作.

我认为问题是代码刀片(foreach)显示我的产品可用的所有颜色.

我该如何解决?谢谢您的帮助!

解决方法:

据我所知,您不是将颜色的集合(数组)传递给视图,而是传递了查询生成器.您需要添加查询执行方法,例如. get()到管道的末尾:

// Adding get() will execute this query
$colors = Color::where('product_id', $id)->orderBy('id', 'asc')->get();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐