【问题标题】:Linking between 2 tables laravel两个表之间的链接laravel
【发布时间】:2016-10-06 10:39:19
【问题描述】:

我有两个表:“products”和“productPhotos”。 每个产品都有一个唯一的 id = Product_ID。 每个 productPhoto 都有一个唯一的 id = ProductPhoto_ID。 在我的表 productPhoto 中也有照片,这在我的迁移中是这样指定的: $table->binary('photo');这是用来上传图片的。

在产品表中,我有 ProductPhoto_ID(这是一个关系)。 但是我必须如何添加“照片”?

【问题讨论】:

标签: laravel relationships


【解决方案1】:

您需要为每个表创建模型。

对于表/列名也最好使用 laravel 约定。

所以我会这样称呼他们:

产品 - ID - 等等...

照片 - ID - product_id - 等等...

然后创建 2 个模型:

    class Product extends Model
    {
        protected $table = 'products';

        public function photos()
        {
          return $this->hasMany('App\Photos');
        }
    }

    class Photo extends Model
    {
        protected $table = 'photos';

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

然后在你的控制器中你就可以得到这样的关系:

$product = Product::find($id)->with('photos');

这将返回一个 Product 模型,其中包含一个名为 photos 的属性,该属性是与其相关的所有照片模型的集合。

看看https://laravel.com/docs/5.1/eloquent-relationships

干杯

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 2016-06-27
    • 2017-07-31
    • 1970-01-01
    • 2013-08-06
    相关资源
    最近更新 更多