Home > OS >  Get the ID of the first parent
Get the ID of the first parent

Time:11-14

I have three models that are related: Article, ArticleBlock, ArticleBlockImage

ArticleBlock is related with Article and ArticleBlockImage is related with ArticleBlock

Here are the relations

Article

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

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');
}

Further in the ArticleBlockImage model I have one function with which I need to get the ID of the current Article in the form of type $article->id

I am trying to do something like this, but I get the error

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

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

CodePudding user response:

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

when you load your relation this way you load the relation type class, not the database records, relation classes like (HasMany, HasOne ...)

to get article_id you can a function like this:

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

CodePudding user response:

You wrote that ArticleBlock is related to Article and to ArticleBlockImage. Then you have the related Article ID inside the ArticleBlock.

That means if you have the ArticleBlockImage $articleBlockImage then you can write:

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

  • Related