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');
}
}
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');
}
This is my Vote model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vote extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function options(){
return $this->hasMany('App\Option');
}
}
this is my Option model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Option extends Model
{
public function vote(){
return $this->belongsTo('App\Vote');
}
public function users(){
return $this->belongsToMany('App\User');
}
}
The case is i want to get the users data from many to many relationship in Option model, but started from Vote model. So i get the options data in the Vote model first, then i get the users data in Option model (many to many)
Laravel has no native support for a direct relationship.
I've created a package for cases like this: https://github.com/staudenmeir/eloquent-has-many-deep
class Vote extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function users()
{
return $this->hasManyDeep(User::class, [Option::class, 'option_user']);
}
}
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'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.
My authenticated user has a color assigned to them via a relationship in the User model.
I would like to go:
return Auth::color()->id;
To return the logged in users color id.
How do I go about doing this?
I also can't do:
Auth::user()->color()->id
or
Auth::user()->color->id
I am getting Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$id
However all relationships are defined.
I am coming from Laravel 4, what am I doing wrong?
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function color() {
return $this->hasOne('\App\Models\Colour');
}
public function salesarea() {
return $this->belongsTo('\App\Models\Salesarea');
}
public function getNameAttribute() {
return $this->first_name." ".$this->last_name;
}
}
Seeing i cant create a comment yet i'll write my question here,
Is this suposed to be a one to many or one to one ?
Is the user_id column present in your color database table ?
if it is a one to many you need to check if:
your user model has this function
public function colors()
{
return $this->hasMany('App\Color');
}
your Color model has this function
public function user()
{
return $this->belongsTo('App\User');
}
If so you should be able to do
Auth::user()->colors witch is a collection of color objects
if it is supposed to be a one to one
you need to check if your user model has this function
public function color()
{
return $this->hasOne('App\Color');
}
your color model has this function
public function user()
{
return $this->belongsTo('App\User');
}
If so you should be able to do
Auth::user()->color witch is a color object
If your user table has a color_id column, then you want a belongs to relation, not a has one. A has one relation is where the other table would have a user_id column (say a profiles table where a profile can only belong to one user). But in your case, I’m assuming a color could be assigned to many users, therefore a user belongs to a color, and a color has many users.
So in this case, you need to change your relationship:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function color()
{
return $this->belongsTo(Color::class);
}
}
You will then be able to query the color from the authentication services:
$color = Auth::user()->color;
Also keep an eye on your model naming, as you used both the American and British English spellings of ‘color’ in your question.