获取第一个parent的ID

Get the ID of the first parent

我有三个相关的模型:Article、ArticleBlock、ArticleBlockImage

ArticleBlock 与 Article 相关,ArticleBlockImage 与 ArticleBlock 相关

这是关系

文章

public function article_blocks()
{
    return $this->hasMany('App\Models\ArticleBlock');
}

文章块

public function article()
{
    return $this->belongsTo('App\Models\Article');
}

public function article_block_images()
{
    return $this->hasMany('App\Models\ArticleBlockImage');
}

ArticleBlockImage

public function article_block()
{
    return $this->belongsTo('App\Models\ArticleBlock');
}

此外,在 ArticleBlockImage 模型中,我有一个函数需要以类型 $article->id

的形式获取当前 Article 的 ID

我正在尝试执行类似的操作,但出现错误

$article = article_block_images()->article_block()->article()->get();

"message": "Call to undefined function App\Models\article_block_images()",

$article = articleBlockImages()->article_block()->article()->get();

当您以这种方式加载关系时,您加载的是关系类型 class,而不是数据库记录,关系 class 类似于 (HasMany, HasOne ...)

要获得 article_id 你可以使用这样的函数:

public function article_id()
    {
        return $this->article_block->article_id; // without brackets
    }

您写道 ArticleBlock 与 Article 和 ArticleBlockImage 相关。然后您在 ArticleBlock 中有相关的文章 ID。

这意味着如果你有 ArticleBlockImage $articleBlockImage 那么你可以写:

$articleId = $articleBlockImage->article_block()->article_id;