Get nested belongstomany in laravel - php

Hello I have a question:
I have three things :
Top Category
Category
Product
I want to have this : Top Category -> Category -> Product
So I can get all nested information to one Top Category
My Models :
class Overcategory extends Model
{
use HasFactory;
protected $fillable = [
'name',
'img',
];
public function categories()
{
return $this->belongstoMany(Category::class);
}
}
class Category extends Model
{
use HasFactory;
protected $fillable = [
'category_title',
'category_description',
'category_preview_img',
'over_categories_id',
'order',
'price'
];
public function product()
{
return $this->belongstoMany(Product::class);
}
public function overcategories()
{
return $this->belongstoMany(Overcategory::class);
}
}
class Product extends Model
{
use HasFactory;
protected $fillable = [
'product_title',
'product_desc',
'product_preview_img',
'product_price',
];
public function category()
{
return $this->belongstoMany(Category::class);
}
}
And my code to get the Top Category with Category is this :
$relationsship = Overcategory::with('categories')->get();
How would I get the categories with their product too?

In order to get all Overcategory with their Category and their Product, you can use the dot notation when you eager load the relationships.
$relationsship = Overcategory::with('categories.product')->get();
// will get you all the Overcategories with a Categories relationshiop and inside each Category, the Products will be loaded.
This also works the exact same way when you are working on eloquent collections instead of a query builder, with the load method instead of with.
If you want to read more on this topic, here is the documentation https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence.
Quick note aside, if a relationship returns multiple items (which is the case with product) it should be plural (products).

Related

Unable to fetch results from hasManyJson Using staudenmeir / eloquent-json-relations

I have been working on two tables Category & Product.
In Category Model I have a relationship like
class Category extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function products(){
return $this->hasManyJson(Product::class,'category_ids[]->id');
}
}
In Products Model I have a relationship like
class Product extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'category_ids'=>'json',
];
public function products(){
return $this->belongsToJson(Category::class,'category_ids[]->id');
}
}
Now in my controller when I'm doing trying to get count of each categories product, it is giving me Empty results, below is my controller code.
public function two_category()
{
$list = Category::where('home_status', true)->get();
foreach($list as $ls){
echo $ls->name.' '.count($ls->products).'<br>';
}
dd('ended');
}
This is giving -
Category1 0
Category2 0
And finally this is how my column in product table looks like.

Laravel Relation based on value within an JSON object

I have two models in which I need to relate to, a Users model and a Prices model. In my Prices model there is a JSON object which holds an ID of a user and I was wondering if I could relate to my Prices table using the ID which is in the Prices model?
I know you could use an getAttribute and then return the user like that, but I was wondering if there is a $this->hasOne() method you could use?
e.g.
JSON
{user_id: 1, other_values:"in the object"}
Prices Model
class Prices extends Model {
/* Prices has the column 'object' which has the JSON object above */
protected $casts = ['object' => 'array'];
public function user(){
return $this->hasOne("App\User", $this->object->user_id, "id"); /* ! Example ! */
}
}
I created a package with JSON relationships: https://github.com/staudenmeir/eloquent-json-relations
Since the foreign key is in the Prices model, you should use a BelongsTo relationship:
class Prices extends Model {
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = ['object' => 'array'];
public function user() {
return $this->belongsTo(User::class, 'object->user_id');
}
}
class User extends Model {
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function prices() {
return $this->hasMany(Prices::class, 'object->user_id');
}
}

Laravel - Select child where param

I have a question with laravel relationship OneToMany. My database have 2 table product and product_entry. Product will have infomation to choose same price... and product_entry will have infomation about infomation.
1 Product have have many product_entry will another language. But site only 1 language in the same time, so have anyway i only choose product_entry have product_entry_language same current language?
Ex: i have 1 product a with language "en" and "es". Normal, current language is "en". In blade, i must foreach product->product_entries and if(product_entry_language == "en") { ** get Info **} => I want don't need run foreach
Model
class Product extends Model
{
use TransformableTrait;
protected $table = 'product';
protected $fillable = ['product_code','product_id'];
public function entries()
{
return $this->hasMany('App\Entities\ProductEntry', 'product_entry_product_id', 'product_id');
}
}
class ProductEntry extends Model
{
use TransformableTrait;
protected $table = 'product_entry';
protected $fillable = ['product_entry_product_id','product_entry_name'];
}
You can do this by
Product::with(['entries' => function ($q) {
$q->where('product_entry_language', \App::getLocale());
}])->get();
\App::getLocale() is the current laravel locale
Use a constraint, for example:
Product::with(['product_entry' => function ($q) use($language) {
$q->where('language', $language);
}])->get();
Where product_entry is relationship name.

How To Update Laravel hasMany Relationship Models?

I've been trying to wrap my head on figuring out how to update my hasMany relationship model. I can easily create new relationships but when I try to update my relationship model it does not work? Does laravel push() method still work? Can anyone help please? For example I want to update my Taxonomy Table thats related to my Products table within my Controller. I have a code snippet below::
Product.php
class Product extends Model
{
protected $fillable = [
'product_category', 'product_subcategory', 'product_name',
'product_price', 'product_id', 'product_description', 'product_image'
];
protected $primaryKey = 'product_id';
public $incrementing = false;
public function addTaxonomiesToProduct()
{
return $this->hasOne('App\Taxonomies', 'product_id', 'product_id');
}
}
Taxonomies.php
class Taxonomies extends Model
{
protected $fillable = ['product_category', 'product_subcategory'];
protected $primaryKey = 'product_id'; // or null
public $incrementing = false;
public function product()
{
return $this->belongsTo(Product::class);
}
}
EditProductController.php
class EditProductController extends Controller
{
public function update(Request $request, Product $product)
{
$product_size = array();
foreach ($request->product_size as $key => $value)
{
array_push($product_size,$value);
}
$product->update([
'product_name' => $request->product_name,
'product_price' => $request->product_price,
'product_description' => $request->product_description,
'product_size' => serialize($product_size),
'product_image' => $product_image_path,
]);
/**
* Go the products table,
* Get the product based off its product_id,
* and then update this products taxonomy
**/
$taxonomies = Product::find($product->product_id);
$taxonomies->addTaxonomiesToProduct->product_subcategory = "Mens Shoes";
$taxonomies->push();
}
}
****Update Issued Solved****
By changing hasMany() to hasOne() within my Products table, my taxonomies table updated correctly.
I think you don't fully understand the way Laravel Eloquent relationships work. First off, you need to define the relationship in both models.. Your Taxonomy model has this, but your Product model should have:
public function taxonomies()
{
return $this->hasMany('App\Taxonomies', 'product_id', 'product_id');
}
Then to update a Product's taxonomies, you'd have something like...Uh, I'm not sure what you're trying to achieve here, especially with the way you chained the product_subcategory, so I can't rightly say, but do see the documentation

Check if category belongs to post

Hello I'm trying to make script that show all categories and if category belongs to post this category should be checked with checkbox. My script wont works could you help me please. It shows only one checked category when have to shows two.
Controller Category model:
class Category extends Eloquent {
protected $table= "categories";
public function posts(){
return $this->belongsToMany('Post');
}
}
Post model
class Post extends Eloquent {
protected $table = 'posts';
public function categories(){
return $this->belongsToMany('Category');
}
}
catRelation:
[{"id":"45","post_id":"132","category_id":"1","created_at":"2014-12-26 20:32:41","updated_at":"2014-12-26 20:32:41"},{"id":"46","post_id":"132","category_id":"3","created_at":"2014-12-26 20:32:41","updated_at":"2014-12-26 20:32:41"}]
all categories: [{"id":"1","name":"Laravel","slug":"laravel","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"},{"id":"3","name":"PHP","slug":"php","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}]
A category shouldn't ever belong to a post, but rather a post should belong to a category.
I assume catRelation is your pivot table. It's worth nothing that you need neither id, created_at or updated_at for this.
Example models:
class Post extends Eloquent
{
protected $table = 'posts';
public function category()
{
return $this->belongsToMany('Category', 'catRelation', 'category_id');
}
}
class Category extends Eloquent
{
protected $table = 'categories';
public function post()
{
return $this->belongsToMany('Post', 'catRelation', 'post_id');
}
}
Note: I may have got the final arguments in belongsToMany the wrong way around.

Categories