没有找到一对多的关系函数


Laravel Eloquent One to Many relation function not found

我有一个模型"model1",它属于另一个模型'model2',它们是一对多关系。假设model2有两个函数

function model1()
{
    return $this->hasMany('App'model1');
}
function model3()
{
    return $this->belongsTo('App'model3');
}

Model1有一个函数,

function model2()
{
    $this->belongsTo('App'model2');
}

当我像下面这样在控制器中调用query时,

function index()
{
    $query=model1::with('model2')->get();
}

它工作但是,

function index()
{
    $query=model1::with('model2.model3')->get();
}

显示以下错误,

调用未定义方法Illuminate'Database'Query'Builder::model3()

因为我刚到laravel,我不明白为什么我不能那样打电话。有人能解释一下吗?

更新::

的场景是:

模型1 =房间

模型2 = Hotel

模型3 = City

客房属于酒店,

酒店有很多房间,

酒店属于城市,

城市有许多酒店,

当我查询房间时,我希望包含Hotel and City。

我有一个模型"房间",属于其他模型"酒店",它们是一对多的关系。假设"Hotel"有两个功能,

function Room()
{
    return $this->hasMany('App'Room');
}
function City()
{
    return $this->belongsTo('App'City');
}

"房间"有一个功能,

function Hotel()
{
    $this->belongsTo('App'Hotel');
}

当我像下面这样在控制器中调用query时,

function index()
{
    $query=Room::with('Hotel')->get();
}

它工作但是,

function index()
{
    $query=Room::with('Hotel.City')->get();
}

显示以下错误,

调用未定义方法Illuminate'Database'Query'Builder::City()

因为我刚到laravel,我不明白为什么我不能那样打电话。有人能解释一下吗?

因为模型1与模型3没有关系,而模型2与模型3有关系。

function index()
{
    $query=model1::with('model2');
}

你也可以这样写

$model1->model2->model3->access_property_x

$model1->model2()->where('something', '=', 'something else')->model3->access_propert_x;