accessing nested relationship in laravel 5 - laravel

i have 3 models like below :
Date
Property
PropertyDetail
and here is my migration for tables i write in order
Date :
public function up()
{
Schema::create('dates', function (Blueprint $table) {
$table->bigIncrements('id');
$table->dateTime('date');
$table->timestamps();
});
}
Property :
public function up()
{
Schema::create('properties', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('type');
$table->text('title');
$table->integer('base_capacity');
$table->timestamps();
});
and PropertyDetail :
public function up()
{
Schema::create('property_details', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('property_id');
$table->string('state');
$table->string('city');
$table->timestamps();
});
}
i tried to remove unnecessarily fields from migration so to keep it clean so here is my 2 relations bettwen date and proeprties
Datemodel :
public function properties() {
return $this->belongsToMany(Property::class);
}
and propery model :
public function dates(){
return $this->belongsToMany(Date::class);
}
public function features(){
return $this->hasMany(Feature::class);
}
ok now finally in my controller i want to do this :
$search = Date::with('properties')
->where('date',$someday)->get()
->and some how here i want to select the city from the property detail table
;
so here is my problem , now i can easily access properties and show thier name but from this relation how can i access features relation and select the city from there should i use joins or some thing there i hope i was clear enough that what i want to do

You can do this:
Property model:
public function details(){
return $this->belongsToMany(Details::class,'property_details','id','property_id');
}
and in Date model:
public function properties() {
return $this->belongsToMany(Property::class);
}
public function propertiesDetails() {
return $this->properties()->with('details');
}
and in your controller you can get detail of properties by use:
$search = Date::with('propertiesDetails')
->where('date',$someday)->get();
now you can access to details of properties.
Hope it helps.

Related

Laravel: cannot insert into many to many relationship

i hope you're having a good day.
so i have this ManyToMany relationship where a user can apply to multiple jobs, and a job can have multiple applicants (users).
here is the table schema
Schema::create('applicant_job', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('job_id');
$table->unsignedBigInteger('applicant_id');
$table->unique(['job_id', 'applicant_id']);
$table->foreign('job_id')
->references('id')
->on('jobs')
->onDelete('cascade');
$table->foreign('applicant_id')
->references('id')
->on('default_users')
->onDelete('cascade');
});
and here is the model code.
DefaultUser.php
class DefaultUser extends Model
{
public function user()
{
return $this->morphOne(User::class, 'userable');
}
public function applications()
{
return $this->belongsToMany(Job::class, 'applicant_job', 'job_id', 'applicant_id');
}
}
and Job.php
class Job extends Model
{
public function owner()
{
return $this->belongsTo(BusinessUser::class, 'business_user_id');
}
public function applicants()
{
return $this->belongsToMany(DefaultUser::class, 'applicant_job', 'applicant_id', 'job_id');
}
}
everything seems ok and find, however when i try to save ( a user applying to a job), i get the following error
i'm doing so inside ApplyToJobController.php
class ApplyToJobController extends Controller
{
public function store(Job $job, Request $request) {
$default_user = auth()->user()->userable;
$job->applicants()->attach($default_user->id);
return redirect("/en");
}
}
and, Thank you very much for your answers.
EDIT
i have changed the column names to this
Schema::create('applicant_job', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('job_id');
$table->unsignedBigInteger('default_user_id');
$table->unique(['job_id', 'default_user_id']);
$table->foreign('job_id')
->references('id')
->on('jobs')
->onDelete('cascade');
$table->foreign('default_user_id')
->references('id')
->on('default_users')
->onDelete('cascade');
});
it made it work, im curios any idea why?
Try to switch the order of the foreign keys in the applicants relation declared in the Job model like the example below :
public function applicants()
{
return $this->belongsToMany(DefaultUser::class, 'applicant_job', 'job_id', 'applicant_id');
}

BadMethodCallException: Trying to list all partners with the categories laravel

I'm experiencing the following:
Goal: I would like to list all partners and the categories they belong to. Basically, it's a many to many relationship.
Below is the code:
Partner Categories Table Migration
public function up()
{
Schema::create('partcats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('partcatnameP')->unique();
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Partners Table Migration
public function up()
{
Schema::create('partners', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('partnername');
$table->string('regnumber')->unique();
$table->unsignedBigInteger('activestatus_id')->unsigned();
$table->foreign('activestatus_id')->references('id')->on('activestatuses');
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Partner_Category Migration
public function up()
{
Schema::create('partner_partcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('partner_id')->unsigned();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
$table->unsignedBigInteger('partcat_id')->unsigned();
$table->foreign('partcat_id')->references('id')->on('partcats')->onDelete('cascade');
$table->timestamps();
});
}
Models are as shown below:
Partcat Model
public function partners()
{
return $this->belongsToMany('App\Partcat','partner_partcat');
}
Partner Model
public function partcats()
{
return $this->belongsToMany('App\Partcat','partner_partcat');
}
and the Partners Controller is as shown below:
public function index()
{
//
$partners = Partner::all()->partcats();
// dd(Partner::all()->partcats());
return view('partners.index',['partners'=>$partners]);
}
This is where I'm trying to retrieve the list of partners and its related categories. However, I get a BadMethod call error.
You can use the following method
$partners = Partner::with('partcats')->get();
https://laravel.com/docs/5.6/eloquent-relationships#eager-loading
A many to many pivot table typically has the id for both tables it is relating.
The Partner_Category migration you have posted only seems to contain a partner_id. You may need to add in the category_id.
public function up()
{
Schema::create('partner_partcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('partner_id')->unsigned();
$table->unsignedBigInteger('partcat_id')->unsigned();
$table->timestamps();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
$table->foreign('partcat_id')->references('id')->on('partcats')->onDelete('cascade');
});
}

Empty array trying to get all the review of product with the product id in the review table

I'm trying to get the review of a product by the product Id in the review table but i do get an empty array or nothing
this are my code.
public function index(Product $product)
{
return $product->reviews;
}
public function product()
{
return $this->belongsTo('App\Model\Product');
}
public function reviews(){
return $this->hasMany(Review::class);
}
migration code
ReviewController
public function up()
{
Schema::create('reviews', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('customer');
$table->integer('star');
$table->text('review');
$table->unsignedBigInteger('product_id')->index();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamps();
});
}
Try this way
$product->with('reviews');

Fetching Relationship Model Data

I have the Below Table Structure
Users table
id- integer
name-string
Casefiles table
id- integer
user_id- foreign_key
name-string
Followups table
id- integer
date- date
casefile_id-foreign_key
I'm using the below Relationship between this models
User.php
public function casefiles()
{
if ($this->hasRole(['sales_executive'])) {
return Casefile::where('user_id', $this->id);
}
}
Casefile.php
public function user()
{
return $this->belongsTo('App\User');
}
public function followups()
{
return $this->hasMany('App\FollowUp');
}
Followup.php
public function casefile()
{
return $this->belongsTo('App\Casefile');
}
I want to fetch Users followups directly. How can i achive this ?
you need to use hasManyThrough() in your User.php you can add this,
public function followUps()
{
return $this->hasManyThrough('App\FollowUp','App\Casefile');
}
then you can normally call the followups using User::with('followUps')->find(1)->followUps
I have noticed that you are checking role in your relationship $this->hasRole(['sales_executive'] this may occur error as you are not if the statement is false. I think you take another approached and handle that as well. for more information on hasManyThrough prefer this link
This should be the case for a HasManyThrough Relationship.
In your case it should be
// Followups migration
Schema::create('followups', function (Blueprint $table) {
$table->bigIncrements('id');
$table->date('date');
$table->unsignedBigInteger('casefile_id')->nullable();
$table->timestamps();
$table->foreign('casefile_id')
->references('id')
->on('casefiles');
});
// Casefile migration
Schema::create('casefiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users');
});
// User.php
public function followups() {
return $this->hasManyThrough(FollowUp::class, Casefile::class);
}
// YourController.php
$user = User::all()->first();
dd($user->followups);

Laravel 5.4 belongsToMany relationship returns empty

In Laravel 5.4 I'am trying to set up a Many To Many Relation. but the belongsToMany returns empty! Here's my migrations and models.
botusers Table:
public function up()
{
Schema::create('botusers', function (Blueprint $table) {
$table->increments('id');
$table->integer('t_id');
$table->string('first_name');
$table->string('last_name');
$table->string('username');
$table->string('mobile');
$table->timestamps();
});
}
candidates Table:
public function up()
{
Schema::create('candidates', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('token');
$table->string('degree');
$table->integer('age');
$table->text('desc');
$table->string('photo_url');
$table->string('cv_url');
$table->timestamps();
});
}
Third table, botuser_candidate Table:
public function up()
{
Schema::create('botuser_candidate', function (Blueprint $table) {
$table->integer('botuser_id');
$table->integer('candidate_id');
});
}
and the votes() method in Botuser Model:
public function votes()
{
return $this->belongsToMany(Candidate::class)->get();
}
When I fire the votes() method returns an empty array. and I also tested bellow method too,
public function votes()
{
return $this->belongsToMany(Candidate::class,'botuser_candidate','botuser_id','candidate_id')->get();
}
What I missed here? What should I do?
Edit:
I also added the foreign keys to the relation but the result is still same!
I would suggest you remove the get() method on the belongsToMany
Then query the database with
$c=new App\Candidate;
$c->with('votes')->get()
if you still want to use $c->votes() then you would have to do some changes to your functions. Lets use scope to achieve it.
public function candidates()
{
return $this->belongsToMany(Candidate::class,'botuser_candidate','botuser_id','candidate_id');
}
public function scopeVotes($query)
{
return $query->with("candidates")->get();
}
Then now we can call $v->votes() and it should return all your record.
Calling get() directly on belongsToMany method will return empty array.

Resources