2 个表之间的链接 laravel

Linking between 2 tables laravel

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

在 table 产品中,我有 ProductPhoto_ID(这是一种关系)。 但是我必须如何添加 'photo'?

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

table/column 名称也最好使用 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');

这将 return 你一个产品模型 属性 称为 photos 是所有与之相关的照片模型的集合。

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

干杯