Laravel morphOne关系总是返回null
我建立了一个一对一(多态)像这样 我的型号:Laravel morphOne关系总是返回null,laravel,eloquent,Laravel,Eloquent,我建立了一个一对一(多态)像这样 我的型号: namespace App; use Illuminate\Database\Eloquent\Model; class Payement extends Model{ protected $table = 'payements'; protected $primaryKey = 'id'; public function payementable(){ return $this->morphTo();
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payement extends Model{
protected $table = 'payements';
protected $primaryKey = 'id';
public function payementable(){
return $this->morphTo();
}}
class Recu extends Model{
protected $table = 'recus';
protected $primaryKey = 'id';
public function payement(){
return $this->morphOne('App\Payement', 'payementable');
}}
我的表格模式
Schema::create('recus', function (Blueprint $table) {
$table->bigIncrements('id');
});
Schema::create('payements', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('numero')->unique();
$table->bigInteger('payementable_id');
$table->string('payementable_type');
$table->timestamps();
});
问题是这是可行的
App\Payement::find(1)->payementable;
此返回为空
App\Recu::find(1)->payement;
这个返回是空的集合
Recu::first()->payement()->get()
您提供的设置没有任何问题。请使用以下数据进行测试:
payements:
---------------------------------------------
|id|numero|payementable_type|payementable_id|
---------------------------------------------
|1 |1 |App\Recu |2 |
---------------------------------------------
recus:
----
|id|
----
|1 |
----
|2 |
----
|3 |
----
更好的做法是使用
无符号
整数作为外键<代码>$table->integer('paymentable_id')->unsigned()代码>但是我不确定它是否会导致您提到的问题。另外,为了更可靠,您可以使用$table->morphs('payementable')代码>在你的迁移文件中。我做了,不工作。我做了这些,所有的事情都是正确的,它工作正常。请注意,如果你想获得recu的付款,你应该首先找到付款表中存在的具有相关id的对象。例如,如果您的recu的id为1,您在payement表中是否有payementable_id=1的记录?App\recu::find(1)->payement;作品你能把表格里的数据扫描一下吗谢谢