F
F
FlooDwm2018-09-01 02:18:39
Laravel
FlooDwm, 2018-09-01 02:18:39

Why does it say there is no such method when getting data from a table through relationships?

There is a CATEGORIES table that is linked to a SUBCATEGORY (1 to many) table, which in turn is linked to a POSTS (many to many) table.
Question: when I call dd( $category->subcategory->post() ) it says there is no such method post() how do I access all POSTS of this CATEGORY via SUBCATEGORIES?
1) The many-to-many connection through does not work because there can be many subcategories for posts and therefore SUBCATEGORIES are associated with many-to-many POSTs, and for many-to-many connection through the subcategory_id field in the POST is required, but it is not there, respectively))))
2) it is impossible to create a CATEGORY_ID column in POST and immediately search for all posts of this category due to some circumstances :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel, 2018-09-01
@FlooDwm

Because in $category->subcategorylies Collection? Well, i.e. you can't get post() from a collection, you first need to pull the model from the subcategory.

$subcategories = $category->subcategory;
foreach($subcategories as $subcat) {
    var_dump($subcat->post)
}

Well, or eager loading And then, too, go through the cycle and get the posts. Well, the relationship, probably, should be called in the plural?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question