Laravel有许多/属于关系

sbtkgmzw  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(79)

我想用laravel连接两个表,但我被卡住了。
我有2个MySSL表

table strans
    + id
    + trans_code
    + trans_description

table step
    + step_id
    + step_trans_code
    + step_proc_sequence

字符串
我的模型看起来像这样:

class Strans extends Model
{
    protected $table = 'hc_strans';
    protected $fillable = [
        'trans_code', 'trans_description', 'trans_sk_code'
    ];
    public function step()
    {
        return $this->hasMany(Sstep::class, 'step_trans_code', 'trans_code');
    }
}
 
 
 class Sstep extends Model
 {
    protected $table = 'hc_sstep';
    protected $fillable = [
        'step_trans_code', 'step_proc_sequence'
    ];
    public function transCode()
    {
       return $this->belongsTo(Strans::class, 'trans_code', 'step_trans_code');
    }
 }


在步骤控制器中,我调用关系:

$step = Sstep::with('transCode')->get();


表中的数据有所有的关系值。但是当我尝试关系时,transCode变量返回空值。我尝试手动查询,没有问题。

"data": [
    {
        "step_id": 8,
        "step_trans_code": "MUT",
        "step_proc_sequence": 80,
        "trans_code": null
    }
]


我在这段关系中做错了吗?

yvt65v4c

yvt65v4c1#

Laravel有一个命名约定,例如在属于关系中它会将外键视为stran_id,因此显式定义外键。

public function transCode()
{
    return $this->belongsTo(Strans::class, 'step_trans_code', 'trans_code');
}

$step = Sstep::with('transCode')->get();

字符串

bf1o4zei

bf1o4zei2#

class Sstep extends Model
{
   protected $table = 'hc_sstep';
   public function transCode()
   {
      return $this->belongsTo(Strans::class, 'step_trans_code', 'trans_code');
   }
}

字符串

hsvhsicv

hsvhsicv3#

另一个答案是,你可以很容易地做到以下没有with

$step = Sstep::first();
$transCode = $setp->transCode;

字符串

相关问题