I am a beginner in laravel i want to create a nested api in which one model is connected with another using hasmany relationship here it is:
Model 1:
class Project extends Model
{
use HasFactory;
protected $table = 'projects';
public $timestamps = true;
protected $fillable = [
'title','description'
];
function categorywithqestions()
{
return $this->hasMany('App\Models\questionmd','cat','id');
}
}
Model 2:
class questionmd extends Model
{
use HasFactory;
protected $table = 'questions';
public $timestamps = true;
protected $fillable = [
'title',
'description',
'cat',
'q_type',
];
function relatedquestions()
{
return $this->hasMany('App\Models\relatedquestion','question_id','id');
}
}
Model 3:
class relatedquestion extends Model
{
use HasFactory;
protected $table = 'related_questions';
public $timestamps = true;
protected $fillable = [
'question_id',
'title',
'description',
];
}
and here is controller:
$callback = function($query) {
$query->where('q_type', '=', 'direct_ask');
};
$questionmd = Project::whereHas('categorywithqestions', $callback)
->with(['categorywithqestions' => $callback])->get();
return response()->json(['message' => 'Success', 'status' => 200,'data'=>$questionmd]);
I want to fetch the related questions also inside the "categorywithqestions" how to do it?
From what i see, you can use hasManyThrough helper.
The database structure should be like this.
1 Project hasMany categories
1 Category hasMany questions
projects
id - integer
name - string
categories
id - integer
project_id - integer
name - string
questions
id - integer
category_id- integer
commit_hash - string
on Project model you can do like this
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
/**
* Get all of the deployments for the project.
*/
public function deployments()
{
return $this->hasManyThrough(Deployment::class, Environment::class);
}
}
later on in you queries you can make
$questions = Project::all()->load('questions');
Please try this way.
$questionmd = Project::whereHas('categorywithqestions', function($q) {
$q->where('q_type', '=', 'direct_ask');
})->with(['categorywithqestions.relatedquestions'])->get();
Related
I have a relationship many to many (between Invoice and Shift) as defined
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'user_id',
'date_ins',
'tas',
];
public function user()
{
return $this->hasOne(User::class,'id','user_id');
}
/**
* The roles that belong to the invoice.
*/
public function shifts()
{
return $this->belongsToMany(Shift::class, 'invoice_shift')
->withPivot(['invoice_id','shift_id', 'shift_taken_id', 'shift_swapped_date','shift_taken_date', 'tas','msg','status_tas']);
}
}
Then Shift model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shift extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'code',
'description',
];
/**
* The users that belong to the role.
*/
public function invoices()
{
return $this->belongsToMany(Invoice::class, 'invoice_shift');
}
}
in the pivot table i have also a column called shift_swapped_date,
I wanted just to retrieve for all invoices the one row that has max value of this date in pivot table.
I tried in the controller
$invoices = Invoice::with('shifts')
->get();
$invoices->max('pivot.shift_swapped_date');
but it doesn't work
I cannot figure out how to do it...
Thx
If that is not working try to run below solution:
$invoices = Invoice::with(['shifts' => function($query) {
$query->max('shift_swapped_date');
}])->get();
So, I have Model who has many uploaded Videos. Model and models_videos are different tables. I need to display video from each model based on their id.
ModelController:
public function index()
{
$models = NewModel::all();
$model_video = NewModelVideos::all();
return view('admin.model_new_videos.index')
->with('models', $models)
->with('model_video', $model_video);
}
Models
class NewModel extends Model
{
protected $table = 'models';
protected $guarded = ['id'];
protected $sortable = ['id', 'name', 'about'];
public function videos()
{
return $this->hasMany('App\Models\NewModels\NewModelVideos','model_id' ,'id');
}
}
class NewModelVideos extends Model
{
use Sortable;
protected $table = 'models_videos';
protected $guarded = ['id'];
protected $sortable = ['id', 'model_id', 'title', 'video'];
public function model()
{
return $this->belongsTo('App\Models\NewModels\NewModel', 'id');
}
}
And View:
#foreach($model_video as $model)
<h1>{{ $model->title }} </h1>
{{ $model->video }}
#endforeach
I can't get video which belongs to specific model. Sorry, I am new and still learning
I think you have to specify the column what is related to NewModel:
class NewModelVideos extends Model
{
use Sortable;
protected $table = 'models_videos';
protected $guarded = ['id'];
protected $sortable = ['id', 'model_id', 'title', 'video'];
public function model()
{
return $this->belongsTo('App\Models\NewModels\NewModel', 'id', 'model_id'); //<-- here
}
}
If you did not specified a foreign key for the models: here is what docs says One To One
Additionally, Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In other words, Eloquent will look for the value of the user's id column in the user_id column of the Phone record. If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key:
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
That is mean that you can do it this way too:
class NewModelVideos extends Model
{
use Sortable;
protected $table = 'models_videos';
protected $guarded = ['id'];
protected $sortable = ['id', 'model_id', 'title', 'video'];
public function model()
{
return $this->hasOne('App\Models\NewModels\NewModel', 'id', 'model_id'); //<-- here
}
}
I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code:
Dish.php
class Dish extends Model
{
protected $quarded = ['id'];
protected $fillable = ['company_id', 'name', 'description', 'enable'];
public $timestamps = false;
public function components()
{
return $this->hasManyThrough('App\DishValues', 'App\Dish', 'id', 'dishes_id');
}
}
DishValues
class DishValues extends Model
{
protected $quarded = ['id'];
protected $fillable = ['dishes_id', 'food_ingredient_id', 'quantity'];
public $timestamps = false;
public function ingredient()
{
return $this->belongsTo('App\FoodIngredient', 'food_ingredient_id');
}
}
FoodIngredient.php
class FoodIngredient extends Model
{
use scopeActiveTrait;
public function scopeVisibleDemo($query)
{
return $query->where('available_in_demo', 1);
}
protected $quarded = ['id'];
protected $fillable = ['company_id', 'name', 'garbage', 'energy_value', 'protein', 'fat', 'available_carbohydrates', 'roughage', 'description', 'url_address', 'allergen', 'available_in_demo', 'enable'];
public $timestamps = false;
}
I get my data:
Dish::with('components')->paginate(25);
How can I get in this code values from FoodIngredient?
This is not working:
Dish::with('components, ingredient')->paginate(25);
or
Dish::with('components')->with('ingredient')->paginate(25);
Given you have multiple relationships, you use :with() with an array of values, not a comma separated string.
This example comes from the docs on "Eager Loading Multiple Relationships" and I've re-named the models based on your example
App\Dish::with(['components', 'ingredient'])->get();
There is also a good blog post that explores the eager/lazy loading of related models in this way.
i have two tables:
**plans:**
planId, plan_name
**Users:**
userId, user_name, password, planId
i tried to get the name of the plan where i select all users.
this is the users model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Users extends Authenticatable {
public $timestamps = false;
protected $table = 'users';
protected $primaryKey = 'userId';
protected $fillable = [
'user_name',
'password',
];
protected $hidden = [
'_token',
];
public function plan()
{
return $this->belongsTo('App\Plans', 'planId');
}
public function validateCredentials( MyUserInterface $user, array $credentials ) {
$plain = $credentials["password"] . $user->getAuthPasswordSalt();
return $this->hasher->check( $plain, $user->getAuthPassword() );
}
}
and this is the plan model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Plans extends Model {
public $timestamps = false;
protected $table = 'plans';
protected $primaryKey = 'planId';
protected $fillable = [
'plan_name'
];
protected $hidden = [
'_token',
];
public function users()
{
return $this->hasMany('App\Users', 'planId');
}
}
when i used:
\App\Users::get();
there is no relations in the output... there is only the users.
what can i do?
i tried to used hasOne and the same issue...
tnx a lot
You can eager load the relationships like this:
\App\Users::with('plan')->get();
Or add a $with property to always eager load it when you fetch an user:
class Users extends Authenticatable
{
protected $with = [
'plan'
];
}
If you don't want to eager load it, you can access the plan of each user's instance like this:
$users = \App\Users::get();
foreach ($users as $user) {
dd($user->plan);
}
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');
}