Laravel 5.4 | Fetching data from Pivot Table - php

I have 4 tables in my database:
Table 1: Category
---|------
id | name
---|------
1 | Cars
In 'Category' model class I have defined the following relationship:
class Category {
public function fields() {
return $this->belongsToMany('App\Field');
}
}
Table 2: Field
id | name
---|-------
1 | Make
In 'Field' model class I have defined the following relationship:
class Field {
public function categories() {
return $this->belongsToMany('App\Category');
}
}
Table 3: Field_Options
field_id | value
---------|-------
1 | Audi
1 | BMW
In 'FieldOption' model class I have defined the following relationship:
class FieldOption extends Model
{
public function field() {
return $this->belongsTo('App\Field');
}
}
Table 4: Category_Field
category_id | field_id
------------|-------
1 | 1
Now I need to fetch all the fields and field_options for category_id=1. How can I achieve this using Laravel?
Thanks!

First define relationship between Field and FieldOptions
public function options() {
return $this->hasMany('App\FieldOption');
}
Then you can eager load all relationships like this
$category = Category::with('fields.options')->find(1);
//Get category 1, with all fields and their respectif fieldOptions

Related

Make conditional Eloquent relationship in Laravel

Laravel 5.7. I have an Eloquent model Theme, with two fields, id and name.
Another model, Filter, has three fields: id, name, theme_id.
Filter:
class Filter extends Model
{
public function theme()
{
return $this->belongsTo('App\Theme');
}
}
I can attach these filters to an arbitrary number of other models, e.g. the model Foo has two fields, id and name. I attach the filter to it using a Filterables table:
Filterables:
id | filter_id | filterable_id | filterable_type
------------------------------------------------
1 | 1 | 3 | App\Foo
The above example shows that the Filter of id 1 is attached to the Foo of id 3.
Now to get all the filters of Foo, I have this relationship in my Foo model:
Foo:
class Foo extends Model
{
public function filters()
{
return $this->morphToMany('App\Filter', 'filterable');
}
}
This all works fine. But now I want to get the Foo model, and only the filters where the filter's theme_id is (for example) 1.
How can I add this condition to the filters relationship?
Just add a where clause directly to your relationship
class Foo extends Model
{
public function filters()
{
return $this->morphToMany('App\Filter', 'filterable')->where('theme_id', 1);
}
}

Laravel variable model polymorphic

I have a table as follows in my database:
table area_blocks;
id
owner_type
owner_id
created_at
updated_at
in the owner_type field it has the Eloquent Model name and the owner_id is the id of that model in the database. Example:
db: area_blocks
id | owner_type | owner_id
1 | App\Models\Title | 3
2 | App\Models\Title | 4
3 | App\Models\Textarea | 1
So I'm expecting when I fetch all of these to also eager load the relevant field from the eloquent model stored in owner_type.
Is there an eloquent relationship that can bring back that record from the owner_type field using eager loading? I've tried $this->morphTo(), e.g.
public function block()
{
return $this->morphTo();
}
but that is returned as null. Any ideas how this can be done?
Example code;
<?php
namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class AreaBlocks extends Model
{
protected $with = ['block'];
public function block()
{
return $this->morphTo();
}
}
Route::get('/', function(){
return App\Models\AreaBlocks::all();
});
You have to specify the column name/prefix:
public function block()
{
return $this->morphTo('owner');
}
Or rename the relationship:
public function owner()
{
return $this->morphTo();
}

How to assign relationship and fetch data using array field in laravel

There are two models: Restaurant and Category
Restaurant{
'_id' : 12345678
'name' : "xyz",
'abstract' : "awdwadawdawdawd",
'category': [1,2,3,4] //category ids
}
Category{
'_id' : 1,
'name' : 'PQR'
}
How can I assign relationship and fetch all the categories using that array field (category) of Restaurant in laravel 5.3 and Database is mongodb?
I am not quite sure about your DB structure, but I think it would be better to create a new pivot table to store the categories of each restaurant in a different row like this:
id | restaurant_id | category_id
1 | 23 | 3
2 | 23 | 5
3 | 25 | 4
As a convention the table should be named 'category_restaurant'
This would be a many to many relationship in laravel.
class Restaurant
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
class Category
{
public function restaurants()
{
return $this->belongsToMany(Restaurant::class);
}
}
Then in your code you can get the ids of a restaurant in this way:
$restaurant = Restaurant::find(1);
$categories = $restaurant->categories;

Eloquent relation pivot table with table

I read the laravel documentation but I couldn't understand very well.
I have this structure on my database.
PriceTable - which contains info about the period of promotional prices and the default price.
Product - which contains info about products.
and PriceTable_Product - which contains the foreign keys of Product and PriceTable and the respective price.
Example:
PriceTable | PriceTable_Product | Product
id | description | PriceTable_id | Product_id | price | product_id| name
1 | default | 1 | 1 | 5.00 | 1 | test
2 | promotional | 2 | 1 | 3.50 |
And at the Order table I can have multiples products, so I want to know if it is possible to relation Order table, with the pivot table PriceTable_Product, because I need the information of which table belongs the price when the product was sold.
First of all you may define the relations between Product and PriceTable.
Product model (App\Product.php)
<?php
namespace App;
class Product extends Model {
protected $table = 'products';
//if the default primary key isn't 'id' you may use $primaryKey
protected $primaryKey = 'product_id';
public function pricetables() {
return $this->belongsToMany('App\PriceTable');
}
}
PriceTable model (App\PriceTable.php)
<?php
namespace App;
class PriceTable extends Model {
protected $table = 'pricetable';
public function products() {
return $this->belongsToMany('App\Product');
}
}
If you created the relations then you can use:
$product = App\Product::find(1);
foreach ($product->pricetables as $pricetable) {
echo $pricetable->pivot->description;
}

Laravel - model modifications

I need to refactor project and I have problem. Below is old, working model, where 'active' column is in "people" table. I need to move 'active' column into "people_translations" table.
Do you have any Idea to modify scopeActive method?
Thanks a lot!
Old working model:
class BaseModel extends Eloquent
{
public function scopeActive($query)
{
return $query->where($this->table . '.active', '=', 1);
}
}
class People extends BaseModel
{
protected $table = 'peoples';
protected $translationModel = 'PeopleTranslation';
}
class PeopleTranslation extends Eloquent
{
public $timestamps = false;
protected $table = 'peoples_translations';
}
Old tables structure:
Table: peoples
id | type | date | active
-------------------------
7 | .... | ... | 1
Table: peoples_translations
id | people_id | language_id | name
-----------------------------------
1 | 7 | 1 | Ann
Old query:
$peoples = \People::active()->get();
New tables structure:
Table: peoples
id | type | date
----------------
7 | .... | ...
Table: peoples_translations
id | people_id | language_id | name | active
--------------------------------------------
1 | 7 | 1 | Ann | 1
Create a relation for translations inside People Model
public function translations()
{
return $this->hasMany('PeopleTranslation', 'people_id');
}
Create active scope in People model
public function scopeActive($query)
{
return $query->whereHas('translations', function($query) {
$query->where('active', 1);
});
}
It will make subquery for this table and as a result it will get where (count of translations with active = 1) > 0.
If you have one-to-one relation - look for hasOne relation method instead of hasMany.

Categories