如何在Laravel中定义多个foreignKey?

时间:2017-08-21 03:48:11

标签: php laravel

在我的Model类中; 目前我已定义为;

  

返回$ this-> belongsTo( 相关 Site :: class,    foreignKey: 'SiteId', ownerKey :'SiteId');; ----->这有效。

但我想将组合定义为外键, 例如:CompanyCode + SiteId

My Current和Target模型都有两列(即:CompanyCode + SiteId)。该组合将返回单个条目。我想在我当前的模型中检索它。

我该怎么做?

我的网站模型就像;

class Site extends Model
{
    protected $table = 'vwSitesPortal';
    protected $primaryKey = 'SiteId';

...

My Current模型就像;

class Alarm extends Model
{
 protected $table = 'vwAlarm';
    protected $primaryKey = 'AlarmId';
...
  public function Site()
    {
       return $this->belongsTo(**related**: Site::class,
**foreignKey**:'SiteId', **ownerKey:**'SiteId'
    }

1 个答案:

答案 0 :(得分:-1)

Schema::create('favorites', function (Blueprint $table) {

$table->integer('lecture_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();

$table->primary(['lecture_id', 'user_id']);

$table->foreign('lecture_id')
      ->references('id')->on('lectures')
      ->onDelete('cascade');

$table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');

});

see this example