Cannot establish relationship between two tables in Laravel - laravel

I want to create a relation between lising and attribute table in laravel for that i have used following code to establish relationship between them but the data in my view is not coming from both the tables. I'm getting following error:
Call to undefined relationship [adListAttributes] on model
[App\Models\AdListing].
Here listing can have as many attribute associated with and attributes
can be associated to many listings
ad_listings:
id
title
name
date
ad_list_attributes table :
id
listing_id
name
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListAttribute extends Model
{
protected $table = "ad_list_attributes";
public function Listings()
{
return $this->belongsToMany('AdListing', 'id', 'listing_id');
}
}
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListing extends Model
{
protected $table = "ad_listings";
public function Attributes()
{
return $this->belongsToMany('AdListAttribute', 'listing_id', 'id');
}
}

Problem is that you are using belongsToMany in both the models.This will cause a problem.
In AdListAttribute model,
public function listing_information()
{
return $this->belongsTo('App\AdListing', 'id', 'listing_id');
}
In AdListing model,
public function adlisting_attributes()
{
return $this->hasMany('App\AdListAttribute', 'listing_id', 'id');
}
You can get the results using,
$response = AdListing::get();
if($response->adlisting_attributes)
{
foreach($response->adlisting_attributes as $attribute)
{
echo $attribute->name;
}
}

Problem is that ur not calling the relationship with the right name i assume
$listings = AdListing::with('Attributes')->get();
Update :
Try this :
use App\Models\AdListAttribute;
//
return $this->belongsToMany(AdListAttribute::class, 'listing_id', 'id');
Same for other model, then try

Related

Property does not exist in collection while using belongsToMany in laravel eloquent

I am using Laravel 8.X and eloquent to develop a web app.
I have a pivot table 'portal_event_users'
I am trying to add a belongsToMany relationship to the portal_users in the model of portal_event_users table.
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class EventUser extends Model
{
use HasFactory;
protected $table = 'portal_event_users';
public function users()
{
return $this->belongsToMany(User::class);
}
public function events()
{
return $this->belongsToMany(Event::class);
}
}
I have the following statements in the controller
$eventusersobj = \App\Models\EventUser::select('*')
->where('event_id', '=', $event_id)
->get();
$response = $eventusersobj->users->keyBy('id');
It is returning the following error
Property [users] does not exist on this collection instance.
Can someone please advice on how can i change this error?
Thanks in advance
As it returns a collection, you can use pluck()
$eventusersobj->pluck('users')->each(function($user){
$user->keyBy('id');
})

laravel where condition with the % operator

today i'm trying to get modulus operator in where laravel clause but i can't get it work and after make some google researches and read the documentation i post this may be some one can help me to get a solution
Produit::has('caracteristique.image', '=', 2)
//->where('(caracteristique.image.caracteristique_id)', '=', 2)
->has('caracteristique.stock')
->where('market_id', Auth()->user()->market->id)
->where(DB::raw('count(`produits`.`caracteristiques`.`images`.`caracteristique_id`)'), '%2', [2])
->get();
i hope to select all products that have a relation with caracteristique table and for each caracteristique i have to find 2 iamge that come from the images table
i make this also
->has('caracteristique.image', '=', 2)
but the problem is this code is not ensure for each caracteristique like i can get 1 product with 2 caracteristique and 3 image but i suppose to have 4 image hope you understand my problem and hope you will help me to find a solution. thank you
here we have the models
produit
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\{
Market,
Caracteristique,
};
class Produit extends Model
{
protected $fillable = ['nom', 'detail', 'rabais', 'statut','demande', 'market_id'];
public function caracteristique()
{
return $this->hasMany(Caracteristique::class);
}
public function market()
{
return $this->belongsTo(Market::class);
}
}
caracteristique
namespace App\Models;
use App\Models\{
Produit,
Stock,
Image,
};
use Illuminate\Database\Eloquent\Model;
class Caracteristique extends Model
{
protected $fillable = [
'produit_id', 'couleur', 'prix', 'quantite', 'size', 'disponible',
];
public function produit()
{
return $this->belongsTo(Produit::class);
}
public function stock()
{
return $this->hasOne(Stock::class);
}
public function image()
{
return $this->hasMany(Image::class);
}
}
image
namespace App\Models;
use App\Models\{
User,
Caracteristique,
};
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $fillable = [
'caracteristique_id', 'user_id', 'nom'
];
public function caracteristique()
{
return $this->belongsTo(Caracteristique::class);
}
public function user(){
return $this->belongsTo(User::class);
}
}
produit can have multiple caracterisque but for each caracteristique it must have 2 images how i can i write this query to avoid query caractristique with one or doesn't have any image please?
and it just say error sql at line one after the %2 condition.

Eloquent one to many relationship not working

I'm stuck for hours with one of those issues where a fresh set of eyes might help. I just can't understand what's missing.
I'm connecting a model called User_ativo and defining two one-to-many relations to models Instituicao and Tipo_Ativo.
My database is simple.
Table user_ativo has columns "tipo_ativo_id" and "instituicao_id". I have a test row where both are set to 1. Both my tables instituicoes and tipo_ativos have only "id" and a string field "nome" (name). Both have a record with id == 1.
User_ativo.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User_ativo extends Model
{
public function tipo(){
return $this->belongsTo('App\Tipo_ativo');
}
public function instituicao(){
return $this->belongsTo('App\Instituicao');
}
}
Instituicao.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Instituicao extends Model
{
protected $table = 'instituicoes';
public function user_ativos(){
return $this->hasMany('App\User_ativo');
}
}
Tipo_ativo.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tipo_ativo extends Model
{
protected $table = 'tipo_ativos';
public function user_ativos(){
return $this->hasMany('App\User_ativo');
}
}
My controller method that fetches the date goes as follow:
public function index()
{
$ativos = User_ativo::with('tipo', 'instituicao')->get();
return view('ativos.index', compact('ativos'));
}
Now here's where it gets interesting, for some reason I can't figure out, when I echo the $ativos variable in my view I get this:
[{"id":1,"user_id":1,"instituicao_id":1,"tipo_ativo_id":1,"tipo":null,"instituicao":{"id":1,"nome":"Banco do Brasil"}}]
So, weirdly my relationship with the Instituicao model works, but the one with Tipo_ativo returns null.
I'm pretty confident someone will point out some dumb and obvious mistake in all of this, but I can't for the life of me understand why one works and the other doesn't since they're pretty much the same thing.
Your relationships names are not according to laravel convention.
Read below function and provide foreign_key and local_key/owner_key to your relationships then it will work
public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null){}
If we do not follow laravel convention while creating relationships then we have to tell it that these are the foreign and local keys that should be used.
Read more here
class User_ativo extends Model{
public function tipo(){
return $this->belongsTo('App\Tipo_ativo','user_ativo_id'); //second parameter is foreign_key_of_User_avito_table_here
}
public function instituicao(){
return $this->belongsTo('App\Instituicao','user_ativo_id'); //second parameter is foreign_key_of_User_avito_table_here
}
}
class Instituicao extends Model
{
protected $table = 'instituicoes';
public function user_ativos(){
return $this->hasMany('App\User_ativo','instituicao_id'); //second parameter is foreign key of Instituicao model
}
}
class Tipo_ativo extends Model
{
protected $table = 'tipo_ativos';
public function user_ativos(){
return $this->hasMany('App\User_ativo','tipo_ativo_id'); //second parameter is foreign key of Tipo_ativo model.
}
}

In laravel how to get the join table data in same array without where condition

I have created both employes and employes_detail tabel with the data
i have created model for both of the table that is given below:
emloye model:
<?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
use App\Http\Model\EmployeDetail;
class Employe extends Model
{
public function employes_detail()
{
return $this->hasOne(EmployeDetail::class);
}
}
and eployedetail model:
<?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
class EmployeDetail extends Model
{
public function employe()
{
public function employe()
{
return $this->belongsTo(Employe::class);
}
}
}
and in controller i used like :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Model\Employe;
use App\Http\Model\EmployeDetail;
class EmployeController extends Controller
{
public function index(Request $request)
{
$Employe=Employe::all();
$convert=$Employe->toArray();
echo "<pre>";print_r($convert);exit;
//return view('employe.employe');
}
}
it showing only employe table data how can i show the data for the
employes_detail as well as .still i am not able to understand it on
laravel documentation can anyone please help me related this.
how can i get the all data from employes and employes_details table for all the records
but when i used this code in controller:
public function index(Request $request)
{
$Employe=Employe::where('id',1)->first();
//$convert=$Employe->toArray();
echo "<pre>";print_r($Employe->employes_detail);exit;
//return view('employe.employe');
}
its shows me the employe_detail table data
but i want both of the table data in a same array and i dont want to use where condition here.
the function employes_detail and employe in your models only declares the relationships between the models but if you want to load the relationship, you can try this :
Employe::with('employes_detail')->get();
or
$employees = Employe::all(); $employees->load('employes_detail');
Then you can access for each employees the relation attribute like that :
foreach($employees as $employe) {
$employe->employes_detail->id;
}
Hopes it helps you.

how to make join query between three tables in laravel

I want to build a query in laravel between three tables (regions, countries, packages) such that table are related together.
regions table contains (id, name, description)
countries table contains (id, region_id, name, description)
packages table contains (id, county_id, pkg_title, pkg_description, price)
I want to select all packages where region_id=1
how can I make query for this situation in laravel query builder. please help me about this question
Set your models as follows.
class Region extends Model
{
}
class Country extends Model
{
public function region()
{
return $this->belongsTo(Region::class);
}
}
class Package extends Model
{
public function country()
{
return $this->belongsTo(Country::class);
}
}
And state following query inside your method.
$region_id = 1;
$PackageWithRegions = Package::with([
'country' => function ($county) use ($region_id) {
return $county->with([
'region' => function ($region) use ($region_id) {
return $region->where('id', $region_id);
}
]);
}
])->get();
// $PackageWithRegions is a collection of packeges with regions where regiion_id = 1
More on eloquent relationships
You can use Eloquent model relationship to prform this, like below
In region controller file
$region = Region::where(['id'=>1])->with(['country'])->get(); ///fetch region with country calls relation declared in region model
In Region.php model
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Region extends Model {
protected $table = 'regions';
public function country(){
return $this->hasOne('App\Models\Country','region_id')->with(['packages']); ///this will fetch country with all pacckages on matching region_id, join of package with country is declared in country model.
}
}
In Country.php model
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model {
protected $table = 'countries';
public function packages(){
return $this->hasMany('App\Models\Package','county_id'); //join of country with packages on county_id
}
}
In Package.php model
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Package extends Model {
protected $table = 'packages';
}
You can see in Laravel doc (https://laravel.com/docs/4.2/eloquent) in section Has Many Through that if you have a model like:
countries
id - integer
name - string
users
id - integer
country_id - integer
name - string
posts
id - integer
user_id - integer
title - string
Then you can access to last relation in this way:
class Country extends Eloquent {
public function posts()
{
return $this->hasManyThrough('Post', 'User');
}
}
Or using customs relations IDs:
class Country extends Eloquent {
public function posts()
{
return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
}
}
So, you can access to the posts of a country:
$posts = Country::get(2)->posts;
// with where:
$posts = Country::where('name', '=', 'USA')->get()->posts;

Resources