I have two entities in my database which are related by a one to many relationship: "User" and "Ad"
I have generated model classes using gii.
This is what I have in my model class for User:
public function getAds()
{
return $this->hasMany(Ad::className(), ['user' => 'id']);
}
and for my Ad model:
public function getUser0()
{
return $this->hasOne(User::className(), ['id' => 'user']);
}
according to Yii2 documentation, In the controller when I do
$ads = Ad::find()->all();
var_dump($ads[0]->user);
It should eagerly load user data from the DB but I only get the foreign key (1).
Even when I try
$ads = Ad::find()->with('user0')->all();
var_dump($ads[0]->user);
Its still the same.
thanks. If I want to send Ads and their related user data by xml in an ActiveController, do I have to do something like this:
$t = array();
foreach ($ads as $ad) {
$t[] = [$ad, $ad->user0];
}
return $t;
Or there is a more straightforward way to do that?
You are still getting Ad objects either with or without eager loading.
The difference is how the relations are populated, with lazy loading the relations are only loaded when they are accessed.
$ads = Ad::find()->all();
foreach ($ads as $ad) {
var_dump($ad->user0); // query to load user record here
}
With eager loading they are populated up front.
$ads = Ad::find()->with('user0')->all();
foreach ($ads as $ad) {
var_dump($ad->user0); // user0 already populated, no query
}
Probably You need joinWith
$ads = Ad::find()->joinWith('user0')->all();
Related
Hi everyone i have a many-to-many relationship between the turnos table and the dias table like this:
Currently, I'm doing the CRUD of the turnos table and for each turnos I have to assign many dias, I did it with the attach method.
Now the issue is in the edit method... how am I gonna get the assigned dias that is related to that turno so I can pass it to the view and the user can edit it?
If someone knows it please help me, I would appreciate it very much
//Dias Model
public function turnos()
{
return $this->belongsToMany(Turno::class);
}
//Turnos Model
public function dias()
{
return $this->belongsToMany(Dia::class);
}
// Controller
public function edit(Turno $turno)
{
// $dias = ??
return Inertia::render('Turnos/Editar', [
'turno' => $turno,
'dias' => ??
]);
}
The edit view Should looks like this:
You can load the relation with the load() method and just return the $turno variable that will contain the "turno" and the "dias".
public function edit(Turno $turno) {
$turno->load('dias');
return Inertia::render('Turnos/Editar', [
'turno' => $turno
]);
}
On the client side you can use v-model to fill your inputs.
I'm in a situation where I need to display the last 5 unique commenters information at the top of the comment list as follows screenshot.
comment image
To do this. I did as follows:
Post Model
public function comments()
{
return $this->hasMany(Comment::class);
}
public function commenter_avatars(){
return $this->comments()->distinct('user_id')
->select('id','post_id','user_id','parent_id')
->whereNull('parent_id')
->with('user')->limit(5);
}
My Controller method as follows
public function index() {
$feeds = auth()->user()
->posts()
->with(['user:id,first_name,last_name,username,avatar', 'media', 'commenter_avatars'])
->orderBy('id', 'desc')
->paginate(10);
return PostResource::collection($feeds);
}
I tried to use groupBy and Distinct.. But did't work as expected.
Did I miss something? or Have there any more best way to solve this?
Thank you in advance!
Noted: I am using latest Laravel (8.48ˆ)
I don't know about your joining of post, user and comments table. But i guess, you can do something similar to following.
At first get latest 5 unique user id of one post:
$userIds = Comments::where("post_id", $post_id)->distinct("user_id")->orderBy("id")
->limit(5)->pluck('user_id');
Then, fetch those user information
$users = Users::whereIn("id", $userIds )->get();
Then, you can return those users
UPDATE
You may use map() to fetch and reorder output. Following is an idea for you:
In Controller:
public function index(Request $request) {
$skipNumber = $request->input("skip"); // this is need for offsetting purpose
$userIds = [];
$feeds = Posts::with("comments")->where("comments.user_id", Auth::id())
->skip($skipNumber)->take(10)->orderBy('comments.id', 'desc')
->map(function ($item) use($userIds){
$users = [];
$count = 0;
foreach($item["comments"] as $comment) {
if(!in_array($comment["user_id"], $userIds) && $count < 5){
$count++;
$userIds.push($comment["user_id"])
$user = User::where("id", $comment["user_id"])->first();
$users.push($user);
}
if($count == 5) break;
}
$data = [
"post" => $item,
"latest_users" => $users
];
return $data;
})->get();
return PostResource::collection($feeds);
}
My code syntax may be slightly wrong. Hopefully you will get the idea.
I have solved this issue by using eloquent-eager-limit
https://github.com/staudenmeir/eloquent-eager-limit
I am having issues with populating Form::select() laravel collective component.
As this question describes :
Foreach inside a Form::select in Laravel 4
I do not have a model for built in methods to get data, I am using guzzle to parse json data with custom methods, so either I do not have the "pluck()" method to pluck only names of something.so is there any other ways ?
Currently I have this, trying to make it work :
public function create()
{
//
$cat_array = null;
$categories = $this->categories->all();
if($categories['success']){
foreach ($categories['message'] as $category) {
$cat_array = array(
$category['cat_name'],
);
}
}
return view('admin.default.pages.categories.create', compact('cat_array'));
}
And in create from :
{{ Form::select('cat_parent_id', $cat_array, null, ['placeholder' => 'None']) }}
Thanks in Advance !
You can still use collection methods but you need to manually make the collection with collect
public function create()
{
//
$cat_array = null;
$categories = $this->categories->all();
if($categories['success']){
$cat_array = collect($categories['message'])->pluck("cat_name")->all();
}
return view('admin.default.pages.categories.create', compact('cat_array'));
}
I am new in Laravel, when I practice I get an error.
at HandleExceptions->handleError('8', 'Trying to get property of non-object', 'C:\xampp\htdocs\cms\app\Http\routes.php', '144', array('id' => '1')) in routes.php line 144
my routes.php file
Route::get('/user/{id}/post',function ($id){
return User::find($id)->post->title;
});
in my User.php file
public function post(){
return $this->hasOne('App\Post');
}
I have two tables 1-posts 2-users
and I have also Post class
I also google and search different sites but can't understand.
Please me,how to rid this Error.
your posts are one user .
this renlship is "one-to-many" relationship .
you must for this reason using this method in modal user :
public function posts()
{
return $this->hasMany('App\Post');
}
one to many is array from posts .
for show resualt you must using foreach :
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
$comment->title ;
}
and reading this links : https://laravel.com/docs/5.2/eloquent-relationships#one-to-many
1:are you shure the relation is one to one;
2:if you shure add primary and foreign key and add this function in Post model.
public function user(){
return $this->hasOne('App\User','id','user_id');
}
I have 3 views (which display settings for each): Users, Groups, Options
Each of these views is successfully rendering, using the below. The controller passes the database info into each view.
#extends('master')
#section('main-title')
Title
#stop
#section('main-content')
// All the divs, content etc (working fine)
#stop
I also have one more view: Settings
The idea of this view is simple, to be an overview of all the settings from the Users, Groups and Options. So essentially I'm trying to pull together each of the 3 views 'main-content' output, and put it within the #section('main-content') within my Settings view. However I have no idea how.
The only option I can think of is to duplicate the content within the Settings view (index function) - however this will cause issues when I want to change something as I'll need to do it in two templates.
My controller:
public function index()
{
$users = User::all();
$options = Option::all();
$groups = Group::all();
return View::make('layouts.settings', array('users' => $users, 'options' => $options, 'groups' => $groups));
}
public function users()
{
$users = User::all();
return View::make('layouts.settings.users', array('users' => $users));
}
public function options()
{
$options = Option::all();
return View::make('layouts.settings.options', array('options' => $options));
}
public function groups()
{
$groups = Group::all();
return View::make('layouts.settings.groups', array('groups' => $groups));
}
Is there anyway, I can say within my Settings view: include the content within 'main-content' from the following views (Users, Groups, Options). Or, use nested view which I have tried but cannot get working.
Thanks in advance.
Here you go - may need fine-tuning: http://paste.laravel.com/xZr