使用现有表模式上的数据透视表在雄辩模型中指定关系字段

问题描述 投票:0回答:1

虽然在Laravel上为枢轴表阅读documentation,但我很难猜测如何在将当前项目的php代码移入/重新设计Laravel时指定适当的字段。

我遇到的问题是,在我现有的项目中,我有下表:

ohimeSama:
id: Primary Key
namae: String

oujiSama
id: Primary Key
namae: String

suki:
id: pk
princess_id: Foreighn Key Ohimesama
prince_id: Foreighn Key Oujisama

对于Ohimesama表,我设置以下模型:

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Suki;
use App\Model\Oujisama;


class Ohimesama extends Model
{
   public $timestamps = false;
   protected $table = "ohimesama";

   public function princesThatShesInLove()
   {
     return $this->belongsToMany(Oujisama::class)->using(Suki::class);
   }
}

Oujisama相同:

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Ohimesama
use App\Model\Suki;

class Oujisama extends Model
{
   public $timestamps = false;
   protected $table = "ohimesama";

   public function lovedByPrincess()
   {
        return $this->belongsToMany(Ohimesama::class)->using(Suki::class);
   }
}

此外,Suki的枢轴模型为:

namespace App\Model;

use Illuminate\Database\Eloquent\Relations\Pivot;

class Suki extends Pivot
{
   public $timestamps = false;
   protected $table = "suki";
}

所以我想知道如何指定代表表suki上的外键的适当关系字段?在文档中,我很难找出如何指定这些字段。

php eloquent pivot-table laravel-5.6
1个回答
0
投票

为了解决问题,您需要遵循以下两个主要步骤:

  1. 通过关系指定枢纽模型Suki中的外键:

namespace App\Model;

use Illuminate\Database\Eloquent\Relations\Pivot;
use App\Model\Oujisama;
use App\Model\Ohimesama;

class Suki extends Pivot
{
   public $timestamps = false;
   protected $table = "suki";

   public function ohimesama()
   {
     return $this->belongsTo(Ohimesama::class, 'princess_id');
   }



   public function ohimesama()
   {
     return $this->belongsTo(Oujisama::class, 'prince_id');
   }
}

  1. 然后在关系定义中,指定要返回的模型的返回pk。使用Pivot作为fk解析器,万一我们将定义我们的Ohimesama模型:
namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Suki;
use App\Model\Oujisama;


class Ohimesama extends Model
{
   public $timestamps = false;
   protected $table = "ohimesama";

   public function princesThatShesInLove()
   {
     return $this->belongsToMany(Oujisama::class,'suki','id','id')->using(Suki::class);
   }
}

如果Oujisama具有pk oujisama_id而不是普通id,则关系定义为:

 return $this->belongsToMany(Oujisama::class,'suki,'id','oujisama_id')->using(Suki::class);

类似,也定义了OujiSama的关系。

© www.soinside.com 2019 - 2024. All rights reserved.