Laravel - Eloquent Relationship not working One to Many relationship - php

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

Related

retrieve data from table based on a foreignKey Laravel

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

How to get data for one to many relationship using Eloquent in Laravel?

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.

Simple way to compare manytomany relationships? Laravel 5.3

I have a set of relationships that looks like this:
The users and agencies have a lot of data stored in them, in addition to the pivot tables you see there.
What I'd like to do is find the agencies or users that match the preferences of the currently logged in individual, whether they are an agency or user.
It's a straight comparison, so nothing fancy. But I honestly have no idea how to write the eloquent query to account for the pivot tables. Can someone point me in the right direction?
I'm looking at something like this, which is understandably failing:
$loggedinagency = Auth::user()->id;
$match_user_agency = User::with('work_prefs')
->where('work_prefs', 'like',
Agency::find($loggedinagency)->work_prefs)
->get();
Edit: The relationships are declared like so:
User:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $table = 'users';
public function work_prefs() {
return $this->belongsToMany('App\Work_Prefs', 'preference_user', 'user_id', 'preference_id');
}
}
Agency:
<?php
namespace App;
class Agency extends Authenticatable
{
use Notifiable;
protected $table='agencies';
public function work_prefs() {
return $this->belongsToMany('App\Work_Prefs', 'agency_preference', 'agency_id', 'preference_id');
}
}
Work Preferences:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Work_Prefs extends Model
{
protected $table = 'work_prefs';
public function user() {
return $this->belongsToMany('App\User', 'preference_user', 'preference_id', 'user_id');
}
public function agency() {
return $this->belongsToMany('App\Agency', 'agency_preference', 'preference_id', 'agency_id');
}
}

How to go deeper with Eloquent hasMany in Laravel 5.2?

I'm trying to get a sort of results collection out from the db, still taking advantage of Eloquent.
I have a table called as_inspections, a table called as_green_areas and a table called as_assets
Each Inspection has a single green area, and each green area has many assets.
When I fetch the inspections I do something like this:
Inspection model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Inspection extends Model
{
protected $table = 'as_inspections';
public function greenAreas()
{
return $this->hasOne('App\GreenArea', 'id');
}
}
GreenArea model
namespace App;
use Illuminate\Database\Eloquent\Model;
class GreenArea extends Model
{
protected $table = 'as_green_areas';
}
Routes
Route::get('inspections', ['middleware' => 'cors', function()
{
$isp = new \App\Inspection();
return $isp
->with('greenAreas')
->get();
}]);
Now I'd like to do something like this:
Route::get('inspections', ['middleware' => 'cors', function()
{
$isp = new \App\Inspection();
return $isp
->with('greenAreas')
->with('assets') // where each green area has its own set of assets
->get();
}]);
As written in the comment, I'd like to get all the assets for that green area, and then all the green areas for that inspection.
How can I do this?
Thanks!
Firs of all your model class and relationship will be defined like this, make sure to replace the foreign keys in the relationship function with correct one in your table,
namespace App; //model class for inspection
use Illuminate\Database\Eloquent\Model;
class Inspection extends Model
{
protected $table = 'as_inspections';
public function greenArea()
{
return $this->belongsTo('App\GreenArea', 'greenareaid','id');
}
}
namespace App; //model for green area
use Illuminate\Database\Eloquent\Model;
class GreenArea extends Model
{
protected $table = 'as_green_areas';
public function inspection()
{
return $this->hasOne('App\Inspection', 'greenareaid','id');
}
public function assets()
{
return $this->hasMany('App\Asset', 'greenareaid','id');
}
}
namespace App; //model for asset
use Illuminate\Database\Eloquent\Model;
class Asset extends Model
{
protected $table = 'as_assets';
public function greenArea()
{
return $this->belongsTo('App\GreenArea', 'greenareaid','id');
}
}
then you can use eager loading of eloquent to easily bring the related models as in the example bellow.. you pass the primary key of the inspection model to find method, and then grab green area and related asset for it
Inspection:find(1)->with('greenArea.assets');
Inspection::find($id)->greenAreas()->assets()->all();
This will fetch all the assets of the greenAreas, inspected by Inspection $id.
I'm not sure which query you're looking for.

Laravel 5 database relationship accessing a data on another table

I have this kind of database design
user_classes
- id
- user_id
- class_schedule_id
class_schedules
- id
- class_id
- date
classes
- id
- name
I am now in my UserClass.php Model File
public function classSchedule() {
return $this->belongsTo('\App\ClassSchedule');
}
public static function getClassByUser($user_id){
$user_class = self::where('user_id','=',$user_id)->with('classSchedule');
//other codes here...
}
My question here is that how can I access the name of the class in the class table since the user_classes table doesn't have a direct access to the class instead it should go through first to the class_schedules table.
I am not sure what Eloquent ORM Relationship should I use.
Your help will be greatly appreciated!
thanks! :)
First of all you will need to rename the third class, from class to something else. Then try this,
class user_classes Extends Eloquent {
function classSchedule() {
return $this->hasMany('Class_schedules','class_schedule_id');
}
}
class class_schedules Extends Eloquent {
function userClasses() {
return $this->belongsTo('user_classes', 'class_schedule_id');
}
function classSomething() {
return $this->hasOne('class_something','id');
}
}
class class_something Extends Eloquent {
function classSchedules() {
return $this->belongsTo('class_schedules', 'id');
}
}
Try and follow the naming conventions within Laravel, that will make your life easier down the road.
It uses the snake_cased version of the plural of your model name to define the table name automagically.
Besides that, when you have a relation with single or plural output, name your relation methods accordingly to describe what they do and what kind of output you can expect.
I prefer a dir /app/Models for the models, hence the namespace, you can change this to /app if that's where your models are.
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserClass extends Model
{
// only defined because laravel auto generates alphabetically
protected $table = 'user_classes';
public function user()
{
// given that User model was moved to app/Models, if not, use \App\User
return $this->belongsTo('\App\Models\User');
}
public function classSchedule()
{
return $this->belongsTo('\App\Models\ClassSchedule');
}
}
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ClassSchedule extends Model
{
public function class()
{
return $this->belongsTo('\App\Models\Class');
}
}
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Class extends Model
{
public function classSchedules()
{
return $this->hasMany('\App\Models\ClassSchedule');
}
}
Now you can basically fetch all entries of UserClass for a particular user, with or without eager loading...
$userClasses = UserClass::where('user_id', $userId)->get();
$userClasses->map(function($userClass) {
echo $userClass->classSchedule->class;
});
More preferably you'll have a method userClasses() with a hasMany relation in your user model

Categories