I have a problem because i make big relation through using join in laravel and I don't know how to use data in this query.
My model:
public function getrelationquery(){
return $this->hasMany('App\Modtwo',"modtwoforeign","id")
->join('Pmodel',"Pmodel.id",'=','Modtwo.pp')
->join("Cpmodel","Cpmodel.pr","=","Modtwo.id")
->join("Ccmodel","Ccmodel.id","=","Cpmodel.cc");
}
My controller:
$q = Mymodel::find($id)->with(array('getrelationquery'=>function($query) use ($id_other){
$query->where('secvar',$id_other);//id_other is the secound variable
}))->get();
$pd = $q;
print_r($pd);
return view('view/displaydata', compact('pd'));
When I use print_r I see all the data but I don't know how display it on view. I need to display data from Ccmodel and Pmodel.
$pd is collection of your object, so you can use foreach to extract your object
#foreach($pd as $data)
{{ $data->column_name }}
#endforeach
Related
I get this error when trying to load a table into my create() function so that the user can select from a list of team_names in the create user page: Call to a member function with() on array
Here is my UserController.php
use Illuminate\Http\Request;
use App\Game;
use App\User;
use App\Team;
...
public function create()
{
$pagetitle = 'Create User';
$teams = Team::orderBy('team_name', 'asc')->get();
if(auth()->user()->user_type !== 'admin'){
return redirect('/')->with('error', "You do not have access to the game you attempted to view.");
}
return view('pages.admin.users.create', compact('pagetitle')->with('teams', $teams));
}
Here is my create.blade.php
#if(count($teams) > 0)
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->team_name}}</option>
#endforeach
#else
<p>No teams found...</p>
#endif
Relationships really should not matter in this case, though I do have all of them properly set up.
For context: I'm creating a "User", but loading all of the "Team" names.
Any help is greatly appreciated.
compact('pagetitle')->with('teams', $teams) is wrong.
compact('pagetitle') returns an array. there is no function called with() on array.
To returns an array contains both pagetitle and teams you can use compact.
compact('pagetitle', 'teams');
That's it.
So,
return view('pages.admin.users.create', compact('pagetitle', 'teams'));
You can use compact() or with() to pass object to view.
return view('pages.admin.users.create',compact('pagetitle','teams'));
OR
return view('pages.admin.users.create')->with('pagetitle',$pagetitle)->with( 'teams',$teams);
I'm trying to loop through the items using eloquent in laravel but I'm getting 0. Please see my code below.
Model
Class Store{
public function products(){
return $this->hasMany('App\Product');
}
}
Controller
$products_count = 0;
foreach($store->products() as $product)
{
if($product->status == 1)
{
$products_count++;
}
}
dd($products_count);
Note: I have data in my database.
You can also use withCount method something like that
Controller
$stores = Store::withCount('products')->get();
or
$store = Store::where('id', 1)->withCount('products')->first();
WithCount on the particular status
$stores = Store::withCount(['products' => function ($query) {
$query->where('status', 1);
}
])
->get();
ref: withcount on relationship
That's because $store->products() returns an eloquent collection which doesn't contain the data from the database yet. You need to do $store->products instead.
If you need to get the count from the database then use
$store->products()->where('status', 1)->count()
With the function-annotation (i.e. products()) you are retrieving the \Illuminate\Database\Eloquent\Builder-instance, not the actual Eloquent-collection.
Instead, you would have to use $store->products – then you will get retrieve the related collection.
In Laravel $store->products() makes you access the QueryBuilder instance, instead there is the Laravel way of doing $store->products, which loads the QueryBuilder and retrieves the collection automatically and down the line is easy to optimise.
I have model named 'PropertyLead' as,
class PropertyLead extends Model
{
public function leadPropertyDetails()
{
return $this->belongsTo('App\Models\Property\Property', 'Property_id','id');
}
public function user()
{
return $this->belongsTo('App\Models\Access\User\User','user_id','id');
}
public function propertyRatings()
{
return $this
->hasMany('App\Models\Property\PropertyRating','Property_id','Property_id');
}
}
In my controller I am trying to get data as ,
$leads = PropertyLead::with('leadPropertyDetails','user','propertyRatings')
->get();
Here in $leads variable i am getting all the data that I want but In 'propertyRatings' I am getting user_id and other details. I also want to get the name user who rated that property using that user_id in propertyRatings object. I am really troubled in this query. Thanks in advance.
Use nested eager loading syntax to load nested relationships:
PropertyLead::with('propertyRatings', 'propertyRatings.user', 'leadPropertyDetails', 'user')->get();
Then you be able to display user name with:
#foreach ($leads as $lead)
#foreach ($lead->propertyRatings as $propertyRating)
{{ $propertyRatings->user->name }}
#endforeach
#endforeach
Suppose I have 3 tables, posts, post_images, and post_links.
post.id is a foreign key in both post_images and post_links.
Each post have multiple images.
I need a data which contains post, its images and its links as single element/array item. If there are 3 posts, I need 3 arrays with each array containing the posts images and links.
My code so far,
$data = DB::table('posts')
->join('post_images','posts.id' ,'=', 'post_images.post_id')
->join('post_links','posts.id' ,'=', 'post_links.post_id')
->select('posts.*')
->get();
with the above query I am getting all the records joined, If i have 3 records with 3 images each, I am getting 9 records, I just need 3 posts with its data as its sub arrays.
Any suggestion?
Here is the PostImage model
class PostImage extends Model
{
public function post() {
return $this->belongsTo(Post::class);
}
}
Here is the PostLink model
class PostLink extends Model
{
public function post() {
return $this->belongsTo(Post::class);
}
}
Here is the Post model
class Post extends Model
{
public function links() {
return $this->hasMany(PostLink::class);
}
public function images() {
return $this->hasMany(PostImage::class);
}
}
In the view you can reach everything you need.
#foreach ($posts as $post)
{$post->title} <br>
#foreach ($post->links as $link)
{$link->url} <br>
#endforeach
#foreach ($post->images as $image)
{$image->src} <br>
#endforeach
#endforeach
And if you want use less queries you could use eager loading to fetch all this data the first time. Eager Loading Laravel
Should look something like this
$posts = Post::with('images','links')->get();
if you already have relation in model you just have to use with method like
$data = PostModel::with('post_images','post_links')->get();
make it dd($data) and look at this. hope it will work.
References: https://laravel.com/docs/5.4/eloquent-relationships#eager-loading
On my website, users can upload images and attach tags to those images.
I've got an images table,a tag table and an images_tag pivot table.
Images can have many tags, and tags can belong to many images.
I want to be able to generate a list of all the tags a user has used in his/her images.
$imageIDs = Images::where('created_by', Auth::user()->id)->lists('id');
So this would create a list of all the image IDs that a user has upload.
What I want is essentially "foreach $imageIDs, check the images_tag table and for every match go to the tags table and get me back the tagname value."
But I have no idea how I'd do that.
Maybe a foreach then use the merge method on all the results? Any help would be appreciated!
You need to use whereHas() to check the relationship:
$userTags = Tags::whereHas('images', function($q) {
$q->where('created_by', auth()->user()->id);
})->get();
Then just pass this data to a view:
return view('some.view', compact('userTags'));
And iterate over tags in a view:
#foreach ($userTags as $tag)
{{ $tag->name }}
#endforeach
What you could do is this.
class Tag extends Model
{
public function images()
{
return $this->belongsToMany(Image::class);
}
}
class SomeController
{
public function someMethod()
{
$tags = Tag::with(['images' => function ($image) {
return $image->where('created_by', Auth::user()->id);
}])->select('id', 'tagname')->get();
// these are your $tags
}
}
You should not use a query inside foreach(). Then it would result N+1 problem. What you instead do is eager loading using with() statement.