Relation multiple Models - laravel

long time i been not working with laravel, im strugling in getting some data.
Im trying to get all the bookmakers from a competition but is not getting:
db:
leagues:
-id
-name
league_bookmakers:
- id
- league_id
- bookmaker_id
bookmakers:
- id
- name
controller:
$example = \App\League::find(440);
dd($example->bookmakers());
Model League:
public function bookmakers()
{
return $this->hasMany(LeagueBookmaker::class);
}

When you call a relation method on a model ($example->bookmakers()), it returns the actual relation, allowing you to add additional constraints.
What you need to be calling is the 'dynamic property', which simply returns the data from the relation as-is:
$example->bookmakers // without the ()

What are you getting? Are you getting an empty collection?
As commented try doing this
dd($example->bookmakers);
Also, try doing dd($example) first and see if it has the bookmakers collection property in it.

When you make relation with league_bookmakers table, you will not get bookmakers data directly. In that case, you can define a belongsToMany Relation like below code -
public function bookmakers()
{
return $this->belongsToMany(Bookmaker::class, 'league_bookmakers','league_id', 'bookmaker_id');
}
It will return bookakers table info directly.

Related

Why does groupBy() work but Count() does not in laravel eloquent model function?

I need to get counts of all the records based on belongsToMany relationship. normally I can use groupBy() in a function inside the model. but if I use count() or withCount() inside a model function, i get the error as followed:
function code:
public function TaskCount(){
return $this->belongsToMany(User::class)->count();
}
Error message:
Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function addEagerConstraints() on int in file /Users/dragonar/Dev/iyw/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 560
If I do the following...
public function TaskCount(){
return $this->belongsToMany(User::class)->Count();
}
//expected record is 4(int)
//output is 4(array) user records.
...it gives me data but like 4 records of the user instead of a number 4. The user data is useless. The only thing needed is totalCount for those records.
Relationship methods have to return Relation type objects. You are returning the result of a query, count() returns a number not the Relation object / Builder. Remove the count from that statement you are returning. Renamed the relationship tasks here.
public function tasks()
{
return $this->belongsToMany(User::class);
// this returns a Relation type object a BelongsToMany object
}
Where you need to use that relationship you can then use count:
$something->tasks()->count();
Or you can load the count of the relationship using loadCount:
$something->loadCount('tasks');
$something->tasks_count;
Or via eager loading for a collection:
$results = Something::withCount('tasks')->get();
foreach ($results as $model) {
echo $model->tasks_count;
}
If you really wanted to you could create an accessor to get the count as well, you just may want to avoid the N+1 issue by preloading the relationship and using the dynamic property to access it in the accessor.
These relation objects are Builders. When you called groupBy on it previously that is returning the Builder, it isn't executing the query. You can add where conditions and order by statements because they are just building the query, not executing it, they return the builder you are calling the method on.
Laravel 6.x Docs - Eloquent - Relationships - Counting Related Models withCount loadCount
Why not use: Task::all()->count(); ?
you can use the withCount method while calling relation like this
User::withCount('images')->get();
You can add get the data and just count it.
public function TaskCount(){
return $this->belongsToMany(User::class)->get()->count();
}
You can call it like
$taskCount = $task->TaskCount();

How to query from database when I have different foreign keys?

I am trying to query data from my database and pass the results to a view called events, the problem I have is that one of my queries will always return the same result because in the where condition the $events_id is the same always. Is there a better way to do the querying? A better logic?
This code is from my controller called EventController:
public function index()
{
$firm_id = DB::table('firms')->where('user_id', auth()->id())->value('id');
$events_id = DB::table('events')->where('firm_id', $firm_id)->value('id');
$events = DB::table('events')->where('firm_id', $firm_id)->get()->toArray();
$actual_events = DB::table('actual_events')->where('event_id', $events_id)->get()->toArray();
return view('events',['events' => $events,'actual_events' => $actual_events]);
}
Since the $events_id is the same every time, the $actual_events will only contain the first result.
The image I have uploaded shows the problem, my table's first three columns are fine. Starting from the fourth they contain repeated values:
As I guess, you need something like this:
$event_ids = DB::table('events')->where('firm_id', $firm_id)->pluck('id');
$actual_events = DB::table('actual_events')->whereIn('event_id', $event_ids)->get()->toArray();
or write about your problem in details and I will try to help you.
you just said that your tables have relation together.
in this case it's better you using the eloquent for that,
first you should type the relations in model of each table like this:
class User extends Authenticatable{
public function cities()
{
return $this->hasmany('App\City'); //you should type your relation
}
}
for relations you can use this link: laravel relationships
after that when you compact the $user variable to your view, you can use this syntax for getting the city value relation to this user: $user->cities;.

Laravel: Model function to check if relationship exists

I have two models Customer, Contact with the following relationship in the Customer model:
public function latestContact () {
return $this->hasOne(Contact::class)->latest();
}
I already found out here that the optional helper is a possible to way check if the relationship exists when displaying the data. Otherwise I would receive a "Trying to get property of non-object" error.
optional($customer->latestContact)->address
Now I am wondering if there is a way to directly check this inside the model function. I would prefer to only call
$customer->latestContact->address
or something like
$customer->getLatestContactAdress
and return false (or no result) if the relationship does not exists.
Thank you in advance.
You could define an accessor or a function within your parent model.
Something like this in your Customer model:
public function getLatestContactAddress()
{
return optional($this->latestContact)->address;
}
And call it like this:
$customer->getLatestContactAddress();
Try using eager loading
$customer = Customer::with('latestContact')->get();
Let me know if not works

Laravel 5.5 retrieving null by nested relation

I have 3 databases:
Routes:
id
name
Rates:
Id
Route_id
Car_id
Cars:
id
name
My model for routes
public function rates()
{
return $this->hasMany('App\Rate', 'route_id');
}
My model for rates
public function car() {
return $this->belongsTo('App\Car','car_id');
}
Now I need to access the car relation, but when I do
return $this->route->with('from','to','rates.car')->paginate(74);
I get null for the car relation
{"id":1,"from_id":1,"to_id":2,"distance":400,"created_at":null,"updated_at":null,"from":{"id":1,"name":"\u0410\u043a\u043a\u043e","created_at":null,"updated_at":null,"lat":32.93310000000000314912540488876402378082275390625,"long":35.0827000000000026602720026858150959014892578125},"to":{"id":2,"name":"\u0410\u0440\u0430\u0434","created_at":null,"updated_at":null,"lat":31.261399999999998300381776061840355396270751953125,"long":35.21490000000000009094947017729282379150390625},"rates":[{"id":1,"route_id":1,"car_id":1,"rate":1123,"night_rate":1391,"car":null},{"id":5551,"route_id":1,"car_id":2,"rate":1123,"night_rate":1391,"car":null},{"id":11101,"route_id":1,"car_id":3,"rate":1123,"night_rate":1391,"car":null},{"id":16651,"route_id":1,"car_id":4,"rate":1123,"night_rate":1391,"car":null},{"id":22201,"route_id":1,"car_id":5,"rate":1123,"night_rate":1391,"car":null},{"id":27751,"route_id":1,"car_id":6,"rate":1123,"night_rate":1391,"car":null},{"id":33301,"route_id":1,"car_id":7,"rate":1123,"night_rate":1391,"car":null},{"id":38851,"route_id":1,"car_id":8,"rate":1123,"night_rate":1391,"car":null}]},
From my understanding you are trying to access a Car model through a Route model.
A couple of things I noticed that should help you find a solution.
First off I think the inverse relation you are supposed to use the belongToMany() function instead.
public function car() {
return $this->belongsToMany('App\Car','Rates'); // Perhaps call the table something like routes_cars to more clearly define it's a pivot table
}
Next I see you are trying to use model functions within the context of $this(). I assume you are doing this in your model? That logic should be in a controller, that might cause some undesired results but I'm not entirely sure. Also it looks like your parameters are incorrect when using with(). You use the function name that you defined in belongsToMany()
App/Route::with('car')->paginate(74);
With the correct relationships setup you rarely need to worry about the pivot table. If you are going to add extra information in the pivot table there are laravel functions to help you do that in the documentation.

using withDefault() on belongsTo results in error

public function featuredimage()
{
return $this->belongsTo(Image::class, 'featured_image_id')->withDefault();
}
this gives me: Call to undefined relationship [featuredimage] on model [App\Models\Core\Blog\Post].
any ideas why?
it should work according to docs:
https://laravel.com/docs/5.4/eloquent-relationships#updating-belongs-to-relationships
Default Models
The belongsTo relationship allows you to define a default model that
will be returned if the given relationship is null. This pattern is
often referred to as the Null Object pattern and can help remove
conditional checks in your code. In the following example, the user
relation will return an empty App\User model if no user is attached
to the post:
public function user()
{
return $this->belongsTo('App\User')->withDefault();
}
my laravel version: 5.4.27
I have two tables:
posts table and images table
inside post table I do this:
$table->biginteger('featured_image_id')->nullable()->unsigned();
$table->foreign('featured_image_id')->references('id')->on('images')->onUpdate('cascade')->onDelete('cascade');
I had the same issue. You need to upgrade to the latest laravel version as the withDefault method is available as from 5.4.28.
To update, simply run:
composer update

Resources