首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Laravel 5.0中关联两个表

如何在Laravel 5.0中关联两个表
EN

Stack Overflow用户
提问于 2016-10-07 02:41:05
回答 1查看 69关注 0票数 1

在一个小示例中,我有3个表(其中2个很重要)。我的表是产品、调拨、仓库

我想要将产品从一个仓库转移到另一个仓库,显然这个转移必须在转移表中,我的示例模型可能是下一个。

HERE THE ENTITY - RELATION - MODEL

现在我使用的是Laravel 5.0,当我创建模型时,我使用的是TRANSFER模型:

代码语言:javascript
复制
<?php namespace Sicem;

使用Illuminate\Database\Eloquent\Model;

类转移扩展了模型{

代码语言:javascript
复制
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'TRANSFER';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['id','ware_ori_id','ware_end_id','product_id'];

public function product(){
    return $this->belongsTo('Sicem\Product');
}//THIS IS OK!
public function sourceware(){
    return $this->belongsTo('Sicem\Warehouse\ware_ori_id');
}//I THINK THIS IS OK!
public function endware(){
    return $this->belongsTo('Sicem\Warehouse\ware_end_id');
}//I THINK THIS IS OK!

}

现在,我的问题是在我的仓库模型中,我不知道我能放什么:

代码语言:javascript
复制
<?php namespace Sicem;

使用Illuminate\Database\Eloquent\Model;

类仓库扩展了模型{

代码语言:javascript
复制
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'WAREHOUSE';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['id','name'];

public function transfer(){

   return $this->hasMany('Sicem\TRANSFER');
}//I supose this.
//But is or not necesary to have 2(two) functions for the relation in my TRANSFER model???????????

}

SICEM:是我的项目名称

请帮帮我。

EN

回答 1

Stack Overflow用户

发布于 2016-10-07 03:01:39

代码语言:javascript
复制
class Product {

  protected $table = 'PRODUCT';

  protected $fillable = ['name'];

  public function transfers()
  {
    return $this->hasMany(Transfer::class);
  }

  public function transfer($warehouse_from_id, $warehouse_to_id)
  {
    return Transfer::create([
      'product_id' => $this->id,
    ]);
  }

}

class Transfer {

  protected $table = 'TRANSFER';

  protected $filalble = ['ware_ori_id', 'ware_end_id', 'product_id'];

  public function warehouse_from()
  {
    retrun $this->belongsTo(Warehouse::class);
  }

  public function warehouse_to()
  {
    return $this->belongsTo(Warehouse::class);
  }

  public function product()
  {
    return $this->belongsTo(Product::class);
  }

}

class Warehouse {

  protected $table = 'WAREHOUSE';

  protected $fillable = ['name'];

}

所以你需要这样做:

代码语言:javascript
复制
$warehouseFrom = Warehouse::find(1);
$warehouseTo = Warehouse::find(2);
$product = Product::find(23);
$product->transfer($warehouseFrom->id, $warehouseTo->id);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39903451

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档