如何在Laravel 5.0中关联两个表

时间:2016-10-06 18:41:05

标签: laravel models has-many belongs-to database-relations

在一个小例子中,我有3个表(其中2个表很重要)。 我的桌子是PRODUCT,TRANSFER,WAREHOUSE

我想将PRODUCT从1个WAREHOUSE转移到另一个WAREHOUSE,显然这个转移必须在TRANSFER TABLE中,我的示例模型可能是下一个。

HERE THE ENTITY - RELATION - MODEL

现在我正在使用Laravel 5.0 当我使用TRANSFER模型创建模型:

<?php namespace Sicem;

使用Illuminate \ Database \ Eloquent \ Model;

类TRANSFER扩展了Model {

/**
 * 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!

}

现在,我的问题出现在我的WAREHOUSE模型中,我不知道我能提出什么:

<?php namespace Sicem;

使用Illuminate \ Database \ Eloquent \ Model;

类WAREHOUSE扩展了Model {

/**
 * 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:是我的项目名称

请帮助我。

1 个答案:

答案 0 :(得分:0)

$scope.submit = function() {
    var record = firebase.database().ref().child('myprofile/'+firebase.auth().currentUser.uid)
                 .set({
                        name: $scope.profile.name,
                        address: $scope.profile.address
                    }

                 ) 
                 .then(function(data) {
                    console.log('profile saved');
                    $scope.profilesaved = "saved";


                 })
                 .catch(function(error) {
                    console.log('profile save failed');
                    $scope.profilesaved = "save-failed";

                 });
};  

所以你需要做这样的事情:

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'];

}