I'm using laravel-eloquent and want to return a collection that joins several tables. For now, I do this using the query builder join method, but I would like to stay within eloquent. I mean, I already defined all my relationships, why should I write joins with foreign keys all the time?
For example, if I have defined my models like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function comments()
{
return $this->hasMany('App\Comments');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
and want to return all the comments with the user names, for now I would write this:
DB::table('users')->select('users.name', 'comments.body')
->join('comments', 'users.id', '=', 'user_id')
->get();
I have tried writing
$users = new 'App\User';
$users->with('comments')
->select('name', 'comments.body');
but it didn't work. Do I need to define a new collection? I will end up with many, many collections if I do that...
Try:
$result = null;
$users = new 'App\User';
$records = $users->with('comments')->get();
if ($records->isNotEmpty()){
$result = $records->map(function($val,$key){
return ["name"=>$val->name, "comments" => $val->comments()->get(['body']);
})->values()->all();
}
dd($result);
I have not tested the codes yet. Please check and let me know if it works for you?
Related
I am trying to get two tables data using join
// $participantstation = DB::table('participant_station')
// ->join('reviews', 'participant_station.id', '=', 'reviews.participant_station_id')
// ->select('reviews.*', 'participant_station.*')
// ->where('station_id',$stn->id)
// ->where('status', '100')
// ;
Still some partipant are not linked , that means - participant_station.id', '=', 'reviews.participant_station_id
if I try this code it only shows the linked participants
is there any way to show both linked and non-linked participants using such query?
Thank you
Assuming you're trying to fetch all the details using Eloquent ORM here's what you can do:
$participantstation= ParticipantStation::join('participant_station', 'participant_station.id', '=', 'reviews.participant_station')->get(['reviews.*', 'participant_station.*']);
This will join the tables
try this,
Model -> ParticipantStation.php:-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ParticipantStation extends Model
{
public function reviews()
{
return $this->hasMany('App\Models\Review');
}
}
Model -> Review.php:-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Review extends Model
{
public function participant_station()
{
return $this->BelongsTo('App\Models\ParticipantStation','participant_station_id');
}
}
In controller.php
use App\Models\ParticipantStation;
$participantstation = ParticipantStation::with('reviews')->where('station_id',$stn->id)->where('status', '100')->get();
//dd($participantstation);
I have the database structure that have a classes table, a users table and users_classes table that matches the other two, because a user can belong to multiple classes. I have a problem now. I have code like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Classes extends Model
{
protected $table = 'classes';
public function students()
{
}
}
And I want to be able to access the students of the class by typing $class = Classes::find(1) and then $class->students to access the students. How do I define the relationship without using the query builder? I want to use eloquent. Im a noobie in Laravel pls dont downvote.
You use a belongsToMany relation.
If your users_classes table has the fields user_id and class_id you can do the following:
public function students()
{
return $this->belongsToMany(Student::class, 'users_classes', 'class_id', 'user_id');
}
I want to simply have a loop which have a sub-loop with all of the images link to the project. project.id = images.model_key in my case.
So i was trying to do something which didn't work.
function index()
{
$projects = Project::all();
foreach($projects as $project)
{
echo "<pre>";
print_r($project->images);
echo "</pre>";
}
}
Im the project model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\ProjectCategoryProject;
use App\Models\Image;
class Project extends Model
{
public $fillable = ['id', 'title','description', 'home_page', 'display'];
public function categories()
{
return $this->hasMany('App\ProjectCategoryProject');
}
public function images()
{
return $this->hasMany('App\Models\Image');
}
...
So i guess i have to specify in the model that project.id = images.model_key but how ?
Error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'images.project_id' in 'where clause' (SQL: select * from `images` where `images`.`project_id` = 4 and `images`.`project_id` is not null)
Thanks, sorry i'm guetting confused.
By default Laravel tries to guess the column name from current model, so in a model Project it will presume the column for it's ids in other models to be project_id. You can however override this and explicitly specity the columns to use for relationship:
public function images()
{
// specify a foreign key to use
return $this->hasMany('App\Models\Image', 'model_key');
}
Or this if you wanna be fully explicit.
public function images()
{
// specify a foreign key to use
return $this->hasMany('App\Models\Image', 'model_key', 'id');
}
I would however strongly encourage you to abide by laravel "convention" for better readability and easier maintenance. If possible, just rename the column :).
my tables:
every part contain many of card.
every card belong to many of part.
now,using laravel eloquent model how can fetch all card for a part without add more column to database
You need to define your relationships like below:
class Part extends Model
{
public function cards()
{
return $this->belongsToMany('App\Cards', 'user_cards');
}
}
Then you can fetch all the cards for a part like below:
$cards = Part::with('cards')->find($part_id);
Part::whereHas('cards', function($query) use ($cardId){
$query->where('id', $cardId);
})->get();
And your model relation should contain like this, for Part.php
public function cards(){
return $this->belongsToMany('App\Card');
}
And for Card.php
public function parts(){
return $this->belongsToMany('App\Part');
}
I'm trying to fetch database data through a model relationship in Laravel.
I've set up one model, like this:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Userskeywords extends Eloquent {
public function relatedKeywords()
{
return $this->hasOne('Keywords', 'id', 'keywordId');
}
}
?>
And the other model is just a normal model. In the database they look like this:
Keywords
UsersKeywords
However, when I run UsersKeywords::with('relatedKeywords')->get() it returns NULLfor related_keywords. This happens when the following code is executed. What am I doing wrong?
$keywords = Userskeywords::where('user', '=', $id)->get();
$keywords->load('relatedKeywords');
return Response::json($keywords);
Your relation is called relatedKeywords so you need to access related object with
$object->relatedKeywords
instead of
$object->related_keywords