So I have 2 tables, articles and sub_categories. They are linked throug Eloquent: articles has many sub_categories's, and sub_categories belongsTo article. They are linked with foreign keys as such: in "article" categorie_id.
How do I retrieve the entire table data article where categorie is "DOG" for exemple
Sorry for the abstraction, but this is the best way I can explain it? :D
article model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Articles extends Model
{
use SoftDeletes;
public function user() {
return $this->belongsTo('App\User') ;
}
public function sous_categories() {
return $this->belongsTo('App\SouCategories') ;
}
}
sub_categorie model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SouCategories extends Model
{
public function categories() {
return $this->belongsTo('App\Categories') ;
}
public function articles() {
return $this->hasMany('App\Articles','cat_id') ;
}
}
in my controller i am trying to fetch data based on the foreign key on the sub_category and foreach sub category i am creating an a array like the mainslider contain articles that have a certain sub_category
public function index()
{
$infos = Infos::all();
$categories = Categories::all();
$articles=Articles::all();
$mainslider=Soucategories::with('articles')->get();
foreach($mainslider as $record){
dd($record->articles);
}
die();
return view('frontEnd.homepage',compact('infos','categories','articles','mainslider'));
}
According to the code you have posted it should be something like
Soucategories::where('title', 'DOG')->with('articles')->get();
it seems there will be only on Soucategory with name "DOG", so you can do something like
Soucategories::where('title', 'DOG')->first()->articles
Related
I have two models with One-to-Many relationship. I want to display data with relationship in blade.
Products Table
Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id
Categories Table
Table name = categories
PrimaryKey = cat_id
Products Model Code
namespace App;
use Illuminate\Database\Eloquent\Model;
class productsModel extends Model
{
//code...
protected $table = 'products';
protected $primaryKey = 'pro_id';
// Every Products Belongs To One Category
public function category()
{
# code...
return $this->belongsTo('APP\abcModel','cat_id');
}
}
Categories Model Code
namespace App;
use Illuminate\Database\Eloquent\Model;
class categoryModel extends Model
{
//code...
protected $table = 'categories';
protected $primaryKey = 'cat_id';
// One Category Has Many Products
public function products()
{
# code...
return $this->hasMany('App\productsModel','cat_id','pro_id');
}
}
Controller Code
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
//code...
public function products($category_id='')
{
# code...
$data["products"] = productsModel::where
('cat_id',$category_id)
->get();
$data["categories"] = productsModel::where
('cat_id',$category_id)->first()->category;
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'APP\categoryModel' not found
Seems that sometimes you have App, sometimes APP, while PHP is not case sensitive on class names, you might use an operating system (Linux?) that is case sensitive in terms of file names.
I would recommend to have only App everywhere, your error message clearly indicates: APP.
You can clearly see in your model files the namespace is written as "namespace App;"
There you defined the namespace for the app folder. So when you are using this model anywhere, you need to write it as you have defined the namespace. Therefore "App\categoryModel".
Your code should be as follows:
public function category()
{
# code...
return $this->belongsTo('App\categoryModel','cat_id');
}
Also a sincere request, as #alithedeveloper mentioned please follow PSR standards for writing code.
public function category()
{
return $this->belongsTo(abcModel::class,'cat_id');
}
public function products()
{
return $this->hasMany(productsModel::class,'cat_id');
}
got a strange scenario here and going to try my best to explain it, i'm basically merging 2 separate systems which are very similar but use different column names.
So, tablea has got one tableb, however tableb is either selected using column id_1 or id_2.
This check is done within a local scope when using the model directly:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Tableb extends Model
{
protected $table = 'tableb';
public function scopeMode(Builder $query, $id)
{
if (env('DEMO_MODE')) {
return $query->where('id1', '=', $id);
}
return $query->where('id2', '=', $id);
}
}
So to using the above model as follows works fine:
Tablea::mode()->first();
However, using this within a relationship then has issues, as the related column name can change, so I must do the same logic within this relationship, but I want to do all of this logic in one place (tableb) to avoid doing it in other relationships:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Tablea extends Model
{
public function Tableb()
{
if (env('DEMO_MODE')) {
return $this->hasOne(Tableb::class, 'id2', 'tableb_id');
}
return $this->hasOne(Tableb::class, 'id1', 'tableb_id');
}
}
Ideas?
An suggestion would be creating a static function on the tableb that returns which id should be used in tablea, something like the following:
(NOTE: I haven't tested the code yet)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Tableb extends Model
{
protected $table = 'tableb';
public function scopeMode(Builder $query, $id)
{
return $query->where(self::getId(), '=', $id);
}
public static function getId()
{
return env('DEMO_MODE') ? 'id2' : 'id1';
}
}
and then
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Tablea extends Model
{
public function Tableb()
{
return $this->hasOne(Tableb::class, Tableb::getId(), 'tableb_id');
}
}
I am pretty new in Laravel and need write a simple backend API.
I am doing smething wrong and I dont know what, because I get some of data from Suppliers table and empty array payments:[ ].
I am trying to get all data from two related tables - PAYMENTS and SUPPLIERS.
It`s a one to many relation SUPPLIERS_ID in PAYMENTS table is connected with ID in SUPPLIERS. Here I give You a graphic representation:
Here`s my code:
Suppliers.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments');
}
}
Payments.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->hasOne('App\Suppliers');
}
}
PaymentsController.php
use App\Payments;
use App\Suppliers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class PaymentsController extends Controller
{
public function index()
{
$payments = Suppliers::with('payments')->get();
return response($payments, Response::HTTP_OK);
}
}
And i get the following answear:
[{"id":1,"name":"Ekonaft","adress":"33-100 Tarnow ","email":"ekonaft#gmail.com","payments":[]},
{"id":2,"name":"Orlen","adress":"Ares testowy","email":"email#email.pl","payments":[]}]
What I`m doing wrong that I get te empty array payments:[ ] on the end of each object?
Try the inverse relationship on payments
belongsTo = has a foreign key to another table
Quoting an example
Should i use belongsTo or hasOne in Laravel?
This is how you can access suppliers from Payments
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo('App\Suppliers');
}
}
This is payments from suppliers
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments','suppliers_ID','id');
}
}
Also, make sure the id's are visible on the output (if id's are hidden, laravel can't work with the relationship). You can also specify the keys on the relationship if you want to use hasOne
Edit: add the keys names within the relation, your fk naming is in capslock
Change you relations like bel
Suppliers.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany(App\Payments::class, 'suppliers_ID', 'id');
}
}
Payments.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo(App\Suppliers::class, 'suppliers_ID', 'id');
}
}
then try again..... :)
You are getting empty array of payments:[] due to miss-matching table relationship key name.
Please, make few changes in both relational function.
public function payments()
{
//return $this->hasMany('App\Model', 'foreign_key', 'local_key');
return $this->hasMany('App\Payments', 'suppliers_id');
}
public function suppliers()
{
//return $this->belongsTo('App\Model', 'foreign_key', 'other_key');
return $this->belongsTo('App\Suppliers', 'suppliers_id');
}
You can learn more about eloquent relationship directly from Laravel documentation for better understanding. https://laravel.com/docs/5.7/eloquent-relationships#one-to-many
Let me know if you still getting same error.
I have the following classes (simplified here) in my Laravel 5.7 model:
VEHICLE.PHP
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vehicle extends Model
{
public function journeys()
{
return $this->hasMany('App\Journey');
}
}
JOURNEY PHP
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Journey extends Model
{
public function vehicle()
{
return $this->belongsTo('App\Vehicle');
}
public function users()
{
return $this->belongsToMany('App\User');
}
}
USER.PHP
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function journeys()
{
return $this->belongsToMany('App\Journey');
}
}
I have an intermediate table (journey_user) between users and journeys (see schema attached).
I can easily get all journeys made by a particular user. But how can I get all vehicles used by a particular user? The standard hasManyThrough method does not appear to work because of the Many to Many relationship between users and journeys.
Thanks for your help!
I haven't tested this out. However, it should be possible to get all vehicles by looping through all the user's journeys, creating an array of vehicles and return this as a collection.
This can be added to your User.php model controller:
/**
* Get all vehicles which user has used
*
*/
public function vehicles()
{
$vehicles = [];
$this->journeys()
->each(function ($journey, $key) use (&$vehicles) {
$vehicles[] = $journey->vehicle;
});
return collect($vehicles);
}
Here, we create an empty array. Then we loop through all the journeys of the users (passing the $vehicles array as a reference to update it).
We use the each() collection method to loop through each journey. We create a new entry to the $vehicles array, adding the vehicle.
Finally, we return all vehicles as a collection.
We can use this in our application like so:
User::find($id)->vehicles();
Note: You could return this as an accessor attribute by changing the function name to setVehiclesAttribute(). This will allow you to access the vehicle field like User::find($id)->vehicle.
How to get data for one to many relationship using Eloquent in Laravel? Actually I followed Eloquent Documentation. But my code returns me an empty array. Here's my work:
Database Schema
Parent Table: mtg_workspace with columns (mw_id[primary key], mw_name,..., mw_access)
Child Table: mtg_workspace_amenities with columns (id[primary key], wa_mwid, wa_name)
Model: MtgWorkspace.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MtgWorkspace extends Model
{
protected $table = 'mtg_workspace';
public $timestamps = false;
public function MtgWorkspaceAmenities(){
return $this->hasMany('App\MtgWorkspaceAmenities', 'wa_mwid');
}
}
Model: MtgWorkspaceAmenities.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MtgWorkspaceAmenities extends Model
{
protected $table = 'mtg_workspace_amenities';
public $timestamps = false;
public function MtgWorkspace(){
return $this->belongsTo('App\MtgWorkspace');
}
}
Controller: WorkspaceController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MtgWorkspace;
use App\MtgWorkspaceAmenities;
class WorkspaceController extends Controller
{
public function index()
{
$workspace = MtgWorkspace::with('MtgWorkspaceAmenities')->get();
return $workspace;
}
}
and here it shows following output:
Can you try defining the primary key for the MtgWorkspace model (as it is not id):
protected $primaryKey = 'mw_id';
I don't think it can match up the children MtgWorkspaceAmenities to the parent MtgWorkspace models as it is trying to use the id attribute on MtgWorkspace to match to the foreign key on MtgWorkspaceAmenities when it spins through the result of the eager loading.
Side Note:
You will have to pass more parameters to the inverse relationship on MtgWorkSpaceAmenities when defining it, as belongsTo() wants to use the calling methods name snake cased with _id added if not told otherwise as the key.