Laravel merge relationships
Try out getter method for property which returns merged collections returned from relations.
public function getCompetitionsAttribute($value)
{
// There two calls return collections
// as defined in relations.
$competitionsHome = $this->competitionsHome;
$competitionsGuest = $this->competitionsGuest;
// Merge collections and return single collection.
return $competitionsHome->merge($competitionsGuest);
}
Or you can call additional methods before collection is returned to get different result sets.
public function getCompetitionsAttribute($value)
{
// There two calls return collections
// as defined in relations.
// `latest()` method is shorthand for `orderBy('created_at', 'desc')`
// method call.
$competitionsHome = $this->competitionsHome()->latest()->get();
$competitionsGuest = $this->competitionsGuest()->latest()->get();
// Merge collections and return single collection.
return $competitionsHome->merge($competitionsGuest);
}
How to merge two eloquent and load relationships
Push elements of $e2
to $e1
collection then use $e1
as you see fit.
foreach ($e2 as $e) {
$e1->push($e);
}
$e1->load('relation');
How to merge hasMany relationships and return a relationship in Laravel?
Eloquent Relationships aren't designed to match one or the other field, they are designed to have one foreign key. You can run a query within your method to get the results you need without relying a relationship.
As discussed in the comments, if you want to re-use that query, contain that logic in a protected function.
protected function allMatchesQuery()
{
// This needs to be wrapped in a nested query or else your orWhere will not be contained in parentheses.
return Match::where(function($q) {
$q->where('team_one_id', $this->id)->orWhere('team_two_id', $this->id);
});
}
public function getMatches() {
return $this->allMatchesQuery()->get();
}
public function getRecentMatches() {
return $this->allMatchesQuery()->orderBy('date', 'DESC')->limit(10)->get();
}
how can we merge multiple relation into one dimensional array using apiresources laravel
Step 1: Define a ComponentLog -> Rfid belongsTo relationship
class ComponentLog extends Model
{
use HasFactory;
public function reader()
{
return $this->belongsTo('App\Models\RfidReader','rfid_reader_id');
}
public function rfid()
{
return $this->belongsTo('App\Models\Rfid', 'rfid_id');
}
}
Step 2: Get the results from ComponentLog to avoid hasMany relationships
$logs = ComponentLog::with(['rfid', 'reader.department'])->get();
Step 3: Map the results
$logs->transform(function ($log) {
return [
'rfid' => $log->rfid->rfid,
'department_name' => $log->reader->department->department_name,
'rfid_reader_id' => $log->rfid_reader_id,
'check_in' => $log->check_in,
'check_out' => $log->check_out
];
});
You can also do it inline.
$logs = ComponentLog::with(['rfid', 'reader.department'])
->get()
->transform(function ($log) {
return [
'rfid' => $log->rfid->rfid,
'department_name' => $log->reader->department->department_name,
'rfid_reader_id' => $log->rfid_reader_id,
'check_in' => $log->check_in,
'check_out' => $log->check_out
];
});
Laravel - How to merge relationship results?
You can load the data and remap it manually using map()
method. I've just tested this code and it works perfectly with hasOne()
relationship:
$users = TournamentUser::where('customer_id', $id)->with('user')->get();
$users->map(function ($i) {
$i->nickname = $i->user->nickname; // Set related nickname.
unset($i->user); // Delete user data from the collection.
return $i;
});
Alternatively, you could use an accessor, but in this case, you'll meet the N+1 problem.
Laravel merge relationship of multiple models into one query
You need to define the relationship between User
and bacheca
. Something like this may work, but you might need to change the foreign and/or local keys to suit your database schema:
class User extends Authenticatable {
public function relazioneFollower() {
return $this->belongsToMany(User::class, 'user_follower', 'follower_id', 'following_id')->withTimestamps();
}
public function bachecas() {
return $this->hasMany(bacheca::class, 'following_id', 'id_utente');
}
}
Then when retrieving the posts it should be as simple as using with()
, but one caveat might be the select()
method. I don't think you can grab the relationship fields from this method. Instead you need to add it to the with()
method. Here's the full request:
$posts = User::with([
'relazioneFollower',
'bacheca.commento:id_post,title,contenuto_post,file,immagine,video,audio,posizione,privacy,created_at,updated_at',
])
->where('user_follower.stato', 2)
->where('user_follower.follower_id', '=', $current_id)
->where(function ($filter) {
$filter->where('privacy', 1);
})
->orWhere(function ($filter) {
$filter->where('privacy', 2)
->where('relazione', 2)
->orWhere('relazione', 3);
})
->orWhere(function ($filter) {
$filter->where('privacy', 3)
->where('relazione', 3);
})
->orWhere(function ($filter) {
$filter->where('privacy', 5)
->where('relazione', 2)
->orWhere('relazione', 3)
->orWhere('relazione', 4);
})
->orderBy('created_at', 'desc')
->select('users.id', 'users.name', 'users.cognome', 'users.fotoProfilo')
->get();
Related Topics
Redirect to Page and Send Custom Http Headers
Finding the PHP File (At Run Time) Where a Class Was Defined
Using Square Brackets in Hidden HTML Input Fields
Gmail Fsockopen(): Ssl Operation Failed Error with Codeigniter and Xampp
Why Are Floating Point Numbers Printed So Differently
Separate Space-Delimited Words in a String
How to Handle Double Quotes in String Before Xpath Evaluation
Class 'App\Http\Controllers\Admin\Auth' Not Found in Laravel 5
Warning: MySQLi_Query() Expects Parameter 1 to Be MySQLi, String Given In
How to Delete Object from Array Inside Foreach Loop
How to Detect Country/Location of Visitor
PHP - Empty $_Post and $_Files - When Uploading Larger Files
How to Send Email with Attachment Using PHP
Getting All Dates for Mondays and Tuesdays for the Next Year