Laravel 5.4 Relationship hasMany not working - php

i have 2 model Article and ArtCategories
I made the one-to-many relation between two model using belongsTo() and hasMany(). hasMany() relation works perfectly but belongTo() doesn't work. Does anyone know where did I make a mistake?
.
Code model
class ArtCategories extends Model
{
protected $table = 'pjt_categories_article';
protected $primaryKey = 'cate_id';
protected $fillable = ['cate_id','categories'];
public function Article(){
return $this->hasMany(Article::class);
}
}
class Article extends Model
{
protected $table = 'pjt_article';
protected $primaryKey = 'article_id';
protected $fillable = ['article_id','title','descriptions','username','cate_id','status','visit','reference'];
public function ArtCategories(){
return $this->belongsTo(ArtCategories::class,'cate_id');
}
public function admin(){
return $this->belongsTo(Admin::class);
}
}
This is DB structure Table up is pjt_article ,table down is pjt_categories_article
Result
$art = Article::findOrFail($article_id);
$cate = ArtCategories::pluck('categories', 'cate_id');
dd($art);
Relation Not working

You should add foreign key in relation method of ArtCategories
class ArtCategories extends Model
{
protected $table = 'pjt_categories_article';
protected $primaryKey = 'cate_id';
protected $fillable = ['cate_id','categories'];
public function article(){
return $this->hasMany(Article::class, 'cate_id');
}
}
Now fetch article with ArtCategories as:
$art = Article::with('ArtCategories')->findOrFail($article_id);
$cate = ArtCategories::pluck('categories', 'cate_id');
dd($art);
As laravel convention Article() method should be articles() and ArtCategories() should be artCategory().

Related

eloquent select all table with relationship many to many

I have 3 tables (workflow, user, workflow_user) and I would like to select the view column of the workflow_user table.
class Workflow extends Model
{
public function user()
{
return $this->belongsToMany(User::class,'workflow_user');
}
}
class User extends Model
{
public function works()
{
//return $this->belongsToMany(Role::class);
return $this->belongsToMany(Workflow1::class,'workflow_user');
}
}
workflow_user table
class WorkflowUser extends Model
{
protected $table = 'workflow_user';
protected $fillable = [
'workflow1_id','user_id','view'
];
protected $primaryKey = 'id';
public $timestamps = false;
}
To get the data from the workflow_user table I do this
$workflow = User::find($idconnect)->works()->orderBy('created_at','desc')->paginate(10);
When I make this request it does not give me the data of the workflow_user(workflow1_id,user_id,view) table.
If you have a model for the pivot table, you should have it extend the Pivot class and use it in the relationship's definition.
Also, you need to manually include the fields that are not the foreign ids in the query result.
class Workflow extends Model
{
public function user()
{
return $this->belongsToMany(User::class, 'workflow_user', 'workflow_id', 'user_id')
->using(WorkflowUser::class)
->withPivot(['id', 'view']);
}
}
class User extends Model
{
public function works()
{
return $this->belongsToMany(Workflow::class, 'workflow_user', 'user_id', 'workflow_id')
->using(WorkflowUser::class)
->withPivot(['id', 'view']);
}
}
workflow_user table
class WorkflowUser extends Pivot
{
protected $table = 'workflow_user';
protected $fillable = ['workflow_id', 'user_id', 'view'];
protected $primaryKey = 'id';
public $incrementing = true;
public $timestamps = false;
}
$workflow = User::findOrFail($idconnect)
->works()
->orderBy('created_at', 'desc')
->paginate(10);

how to access a function from model file

im using laravel 7.24 and php 7.4 on my project
What i want to is fundementally creating relations between 3 table and using them in 'one' query.
to be specific i need to access 'ordered products' from my order detail page.
public function orderdetail($id)
{ //certainorder model access to 'ShoppingCard'model from below
$orderDetails = CertainOrder::with('ShoppingCard.shoppingCardProducts.product')
->where('ShoppingCard.id' , $id)->firstorFail();
return view('orderdetails', compact ('orderDetails'));
}
CertainOrder model access to 'ShoppingCard' model from top and in the ShoppingCard model it contains shoppingCardProducts function which you will see in below and with shoppingCardProducts function my 'products' table had a relation. the problem is something in relations is wrong and i can't get data from shoppingcardproduct
class ShoppingCard extends Model
{
protected $table = "shopping_card";
protected $fillable = ['id', 'user_id', 'created_at','updated_at'];
public function shoppingCardProducts()
{
return $this->hasMany('App\ShoppingCardProduct');
}
class CertainOrder extends Model
{
protected $table = "certain_orders";
protected $guarded = [];
public function shoppingCard()
{
return $this->belongsTo(ShoppingCard::class, 'sepet_id');
//sepet_id is a foreign key.
}
class ShoppingCardProduct extends Model
{
use SoftDeletes;
protected $table = "shopping_card_product";
protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];
public function product()
{
return $this->belongsTo('App\Product');
}
I think you missed it somewhere in the code
class ShoppingCard extends Model
{
protected $table = "shopping_card";
protected $fillable = ['id', 'user_id', 'created_at','updated_at'];
public function shoppingCardProducts()
{
return $this->hasMany('App\ShoppingCardProduct');
}
public function CertainOrder(){
return $this->hasMany('path\to\model');
}
public function ShoppingCardProduct(){
return $this->hasMany('path\to\model');
}
}
class CertainOrder extends Model
{
protected $table = "certain_orders";
protected $guarded = [];
public function shoppingCard()
{
return $this->belongsTo('App\path\to\model', 'sepet_id');
//sepet_id is a foreign key.
}
}
class ShoppingCardProduct extends Model
{
use SoftDeletes;
protected $table = "shopping_card_product";
protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];
public function ShoppingCard()
{
return $this->belongsTo('App\ShoppingCard');
}
}
and make the call this way
public function orderdetail($id)
{ //certainorder model access to 'ShoppingCard'model from below
$orderDetails = ShoppingCard::with('CertainOrder, ShoppingCardProduct')
->where('id' , $id)->firstorFail();
return view('orderdetails', compact ('orderDetails'));
}

How to get the relation in laravel

I have three model : Manager ,Vendor, Banquet
and the relationship is :
manager has one vendor
vendor has many banquet
How to get the all manager with all relation in laravel orm?
$manager = Manager::where('active',1)->get();
$vendor = $manager->vendor()->get();// -- dose not work!
$banquet = $vendor->banquet()->get();// -- dose not work!
Manager model:
class Manager extends Model{
protected $table = 'manager';
protected $primaryKey = 'id';
public function vendor(){
return $this->hasOne('ACME\Entities\Vendor','managerId','id');
}
}
Here is the model
Vendor model:
class Vendor extends Model{
protected $table = 'vendor';
protected $primaryKey = 'id';
public function manager(){
return $this->belongsTo('ACME\Entities\Manager_V','id','managerId');
}
public function banquet(){
return $this->hasMany('ACME\Entities\V_Banquet' ,'vendorId' ,'id');
}
}
Banquet model:
class Banquet extends Model{
protected $table = 'banquet';
protected $primaryKey ='id';
public function vendor()
{
return $this->belongsTo('ACME\Entities\Vendor' ,'vendorId' ,'id');
}
}
That didn't work because get() gives the collection of managers. Vendor hasmany banquets so, banquets() in vendor model would be good convention. And You should do something like this:
$managers = Manager::where('active',1)->with('vendor','vendor.banquets')->get();
foreach($managers as $manager)
{
$vendor=$manager->vendor;
print_r($vendor);
foreach($vendor->banquets as $banquet)
{
print_r($banquet);
}
}
Use with method
$manager = Manager::with(['vendor','vendor.banquet'])->where('active',1)->get();
You will be able to get data as
$banquet = $manager->vendor->banquet;
// $banquet will be array of banquet model objects
Remember hasMany return array, hasOne return Object and belongsTo return Object.

Laravel MongoDB hasMany relationship is not working

I'm try to create a relationship between albums and photos (an Album has many photos). Below is my controller and what my models look like. Interesting enough, the reverse relationship photo->album (belongsTo) works fine! but the album->photos returns an empty collection.
## The hasMany relationship does NOT work... I get an empty collection
<?php
class AlbumController extends BaseController
{
public function show(Request $request, $album_id)
{
$album = Album::find($album_id);
dd($album->photos);
}
}
## Results:
# Collection {#418
# items: []
# }
## The belgonsTo relationship works
<?php
class PhotoController extends BaseController
{
public function show(Request $request, $photo_id)
{
$photo = Photo::find($photo_id);
dd($photo->album);
}
}
<?php
namespace App;
use DB;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use Moloquent;
class Album extends Moloquent
{
use RecordActivity, SoftDeletes;
protected $connection = 'mongodb';
protected $table = 'albums';
protected $collection = 'albums';
protected $primaryKey = "_id";
protected $dates = ['deleted_at'];
protected $fillable = ['user_id','name','is_private'];
public function photos()
{
// Neither seems to work
//return $this->embedsMany('Photo');
return $this->hasMany('App\Photo');
}
}
<?php
namespace App;
use DB;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use Moloquent;
class Photo extends Moloquent
{
use RecordActivity, SoftDeletes;
protected $connection = 'mongodb';
protected $table = 'photos';
protected $collection = 'photos';
protected $primaryKey = "_id";
protected $dates = ['deleted_at'];
protected $fillable = ['album_id', 'user_id', 'name', 'folder', 'is_private', 'caption'];
protected $hidden = [];
// user and album belongsTo works
public function user()
{
return $this->belongsTo('App\User');
}
public function album()
{
return $this->belongsTo('App\Album');
}
}
The issue had to do with the fact that my IDs were ObjectID and it seems to be an issue with Jessengers Laravel MongoDB Drivers... we have actually decided to move back to MariaDB to fully utilize Eloquent/Relationships
I did the same thing as yours and i found that nothing wrong with Mongodb. Because Mongodb defined the "_id" as primary key and that's the reason it couldn't get the correct relationship: belongsTo and hasMany. So i did a small change by declared the $primaryKey = "id" on the top of parent Model and it worked fine
this worked for me.
/**
* #return HasMany
*/
public function tasks(): HasMany
{
return $this->hasMany(ProjectTask::class, 'project_id', 'idAsString');
}

Laravel 4 model relationship through another model

I'm trying to bind multiple models to a form. Currently, I have 4 models:
<?php
class DemDataSet extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'DEMDataSet';
protected $primaryKey = 'pk_DEMDataSet';
public function DemographicReport(){
return $this->hasOne('DemographicReport','fk_DemDataSet','pk_DemDataSet');
}
}
class DemographicReport extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'DemographicReport';
protected $primaryKey = 'pk_DemographicReport';
public function DemDataSet(){
return $this->belongsTo('DemDataSet','fk_DemDataSet','pk_DemDataSet');
}
public function dAgency(){
return $this->hasOne('dAgency','fk_DemographicReport','pk_DemographicReport');
}
}
class dAgency extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'dAgency';
protected $primaryKey = 'pk_dAgency';
public function DemographicReport(){
return $this->belongsTo('DemographicReport','fk_DemographicReport','pk_DemographicReport');
}
public function dAgency_10(){
return $this->hasMany('dAgency_10','fk_dAgency','pk_dAgency');
}
}
class dAgency_10 extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'dAgency_10';
protected $primaryKey = 'pk_dAgency_10';
public function dAgency(){
return $this->belongsTo('dAgency','fk_dAgency','pk_dAgency');
}
}
?>
And I'm passing it to my view through my controller like so:
public function index()
{
//THIS is the line I need help with (I think):
$agency = dAgency::with('dAgency_10','DemographicReport')->find(1);
//for troubleshooting:
echo "<pre>",print_r(dAgency::with('dAgency_10','DemographicReport')->find(1)->toArray()),"</pre>";
return View::make('test')
->with('agency', $agency);
}
I'm able to bind everything except for data from the DemDataSet model, which I can't even figure out how to establish the relationship between it and my dAgency model. So basically, I just want the fields in the DemDataSet model to be available to my view, then obviously I want to be able to perform all the CRUD operations eventually.
Looking at your models, you should just be able to access it via the DemographicReport.
i.e.,
$dataset = $agency->DemographicReport->DemDataSet;

Categories