【发布时间】:2018-04-03 01:33:47
【问题描述】:
我使用的是 laravel 5.4,有两个模型 ParentAccount 和 ChildAccount, 父母有很多孩子
父母
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ParentAccount extends Model
{
//
public $timestamps = false;
protected $table = 'parent_accounts';
protected $fillable = [
'name', 'account_id'
];
public function childs()
{
return $this->hasMany('App\ChildAccount','account_id', 'parent_id');
}
}
孩子
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ChildAccount extends Model
{
//
public $timestamps = false;
protected $table = 'child_accounts';
protected $fillable = [
'name', 'account_id','parent_id'
];
}
当我使用 echo ParentAccount::find(1)->childs(); 尽管所有父母都有孩子,但我在 null 上调用成员函数 childs() 时收到错误消息
注意:child 有 parent_id,它是 parent 中的 account_id
【问题讨论】:
-
将父模型和子模型的主键改为
account_id而不是id!! -
@Maraboc 但我已经在 hasmany 函数中定义了它,所以我不需要它,对吧?
-
不,事实并非如此,因为在documentation 你有
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention. -
@Maraboc 是的,如果使用 find(1),那将是必需的,但如果使用 all(),它也不起作用!
-
$result = ParentAccount::whereAccountId(1)->with('childs')->get();