【问题标题】:Get the ID of the first parent获取第一个父母的ID
【发布时间】:2021-12-25 10:10:59
【问题描述】:

我有三个相关的模型: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": "调用未定义函数 App\Models\article_block_images()",

【问题讨论】:

    标签: laravel relationship


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:
      $article = articleBlockImages()->article_block()->article()->get();
      

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

      要获取 article_id,您可以使用如下函数:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-03
        • 2010-12-16
        • 2011-08-10
        • 1970-01-01
        • 2014-11-14
        • 1970-01-01
        • 2013-03-06
        • 2013-06-23
        相关资源
        最近更新 更多