I have three tables that are the following users, mapas, marcadores
A user has several mapas
a mapa has several marcadores
What I'm trying to do is show the marcadores that belong to the mapas of the user who has logged in.
this are the tables and relationship
This is the function in the controller that I am working on:
public function index()
{
$mapas = Mapa::orderBy('id', 'DESC')->where('user_id', auth()->user()->id);
$marcadores = Marcador::orderBy('id', 'DESC')->where('mapa_id');
return view('user.marcadores.index', compact('marcadores'));
}
thanks for your help
You are trying to get all the mapas id first and then filter marcadores according to those id's. Try using the code below for that:
public function index()
{
$mapas = Mapa::orderBy('id', 'DESC')->where('user_id', auth()->user()->id)->pluck('id')->toArray();
$marcadores = Marcador::orderBy('id', 'DESC')->whereIn('mapa_id', $mapas)->get();
return view('user.marcadores.index', compact('marcadores'));
}
You can use JOINS for this. Try the next code (maybe the syntax is not the correct one, but take the idea):
public function index()
{
$marks = DB::table('mapas')
->join('marcadores', 'marcadores.mapa_id', '=', 'mapas.id')
->where('mapas.user_id', auth()->user()->id)
->select('marcadores.*')
->orderBy('marcadores.id', 'DESC')
->get();
return view('user.marcadores.index', compact('marks'));
}
The easiest and Laravel standard way to do this is create a hasManyThrough relationship from User to Marcadores
UserModel
class User extends Model
{
public function marcadores()
{
return $this->hasManyThrough(Marcadores::class, Mapas::class);
}
}
Controller
public function index()
{
$marcadores = auth()->user()->marcadores;
return view('user.marcadores.index', ['marcadores' => $marcadores]);
}
Related
I have two models User and Child.
class User extends Model {
public function children() {
return $this->belongsToMany('App\Child', 'user_child')->withPivot('relation_id');
}
public function connections() {
// How to get the distinctly aggregate of my children.friends.contacts as a relationship here?
}
}
class Child extends Model {
public function contacts() {
return $this->belongsToMany('App\User', 'user_child')->withPivot('relation_id');
}
public function friends() {
return $this->belongsToMany('App\Child', 'child_connection', 'child_id1', 'child_id2');
}
}
I would like to eagerly load the distant relationship which I name 'connections' which are the contacts (users) of my children's friends.
$user = User::with('children', 'children.friends', 'connections');
Any ideas how to do this elegantly?
Thank you!
Try
public function connections() {
return $this->belongsToMany('App\Child', 'user_id')->with('friends.contacts;);
}
OMG What a long shot!
If by any miracle that works, then doing
$user = User::find(1);
$user->connections(); //should bring 'children', 'friends' and 'contacts' in one query.
Well it should.
If you find an answer, please post it. I'm really interested in this.
A User has many Auktion and Gebot.
A Gebot belongs to one Auktion and one User
I want to fetch all Auktion where the User also has a Gebot
Something like:
Auth::user()->gebote->auktionen->orderBy('end_time');
The orderBy() should be executed on the Auktionen retreived via Gebot, which is not possible because the relationship between Auktion and Gebot is one-to-many:
**Gebot Model**
public function auktion()
{
return $this->belongsTo('App\Auktion');
}
public function user()
{
return $this->belongsTo('App\User');
}
**Auktion Model**
public function gebote()
{
return $this->hasMany('App\Gebot', 'auktion_id');
}
public function user()
{
return $this->belongsTo('App\User');
}
What is the proper relationshsip setup and query to achieve this?
EDIT:
My current approach is this
#foreach (Auth::user()->gebote as $gebot)
<?php $auktion = $gebot->auktion;
if($auktion->anzeigentyp_id == 2)
continue; ?>
#include('shop/row')
#endforeach
which is not very clean as I am fetching all entries first and I can't orderBy()
Use whereHas() which will filter your relation by it's subrelation. Auktion must have relation smth like hasMany() to gebots
$userId = Auth::user()->getKey();
App\Auktion::whereHas('gebot', function ($query) use($userId) {
//here you need to filter gebots which belongs to user
$query->where('user_id', $userId);
})->orderBy('end_time')->get();
Heres what i am doing.
$question = ForumQuestion::where('link',$ques)->with('answers')->first();
$answers = $question->answers;
$answers->load('user');
//return $answers;
return view('forum.question', compact('question','answers'));
the $answers->load('user'); eager loads corresponding user of the answer.
public function user()
{
if ($this->user_type == 'student') {
return $this->belongsTo(Student::class, 'user_id');
}else{
return $this->belongsTo(Teacher::class, 'user_id');
}
}
But problem is $this->user_type gets some kind of static. If my first answer has user_type = 'teacher' then in every query it assumes as it is teacher even though it changes some time to student.
Why it is static? If I don't eager load it works well.
What if you change your eager loading into two different categories instead of putting everything together into the user function
public function student() {
return $this->belongsTo(Student::class, 'user_id');
}
public function teacher() {
return $this->belongsTo(Teacher::class, 'user_id');
}
and just if you really want to do an if statement, call it from a different function such as user. Hope that helps.
Im new in Laravel 4, and right now im coding for small project, i use laravel as framework to build my website, but my code i always wonder it's optimize or not because in my model i just wrote:
Category Model
public function parents()
{
return $this->belongsTo('Category', 'cat_father');
}
public function children()
{
return $this->hasMany('Category', 'cat_father');
}
}
Post Model:
<?php
class Post extends BaseModel{
public $table = "post";
protected $primaryKey = 'idpost';
public function Category()
{
return $this->belongsTo('Category', 'cat_id');
}
}
because i didn't know how to join 2 tables in laravel 4, i have a condition is find all post from my categories, which it hadn't belong to category name "Reunion", but i didn't know how to do that, therefore i wrote 2 lines code for that purpose (im not sure wrote code in controller is best way but i didn't know how to call method from Model to controller and get return value)
My method from controller for select all post, it hasn't belong to category name "Reunion"
public function getAllPostView()
{
$getCat = Category::where('cat_name','=', 'Reunion')->firstOrFail();
$post = Post::where('cat_id', '!=', $getCat->idcategory)->get();
return View::make('layouts.post')->with('post',$post);
}
My question, my code is optimize when i wrote it in controller? and how to wrote it in model and get parameter for passing it to controller and use it to view.
second question is how to order "POST" because some cases post need to be ordered from new to old
This is how you do it:
$exclude = 'Reunion';
$posts = Post::select('posts.*')->join('categories', function ($j) use ($exclude) {
$j->on('posts.cat_id', '=', 'categories.idcategory')
->where('categories.name', '<>', $exclude);
})->get();
could just use simple joins
public function getAllPostView()
{
$getCat = Category::where('cat_name','=', 'Reunion')
->join('post','post.cat_id', '!=','Category.idcategory')->get();
return View::make('layouts.post')->with('post',$post);
}
Look out for same field names in both the tables if so can use select
$getCat = Category::select('Category.idcategory as cat_id','Category.cat_id as pos_id','many other fields')
// 'as cat_id' not required for unique field names
->join('post','post.cat_id', '!=','Category.idcategory')
->where('cat_name','=', 'Reunion')
->get();
I have three tables - Campaigns, Actions and Activists. A Campaign has many Actions, and an Action belongs to both an Activist and a Campaign.
Each action has a client_id (from the client_id of the campaign it belongs to), so when a client views a list of activists, they should only see those who have taken an action on one of their campaigns.
Likewise, when viewing an individual activist, they should only see those actions related to their campaigns.
Models
Campaign.php
public function actions()
{
return $this->hasMany('Action');
}
Action.php
public function campaign()
{
return $this->belongsTo('Campaign', 'campaign_id');
}
public function activist()
{
return $this->belongsTo('Activist', 'activist_id');
}
Activists.php
public function actions()
{
return $this->hasMany('Action');
}
Controllers
ActivistsController.php
public function index()
{
$activists = Activist::with('actions')->whereHas('actions', function($q) {
$user = Sentry::getUser();
$q->where('client_id', $user->client_id);
}))->get();
foreach ($activists as $activist)
{
$activist->total = $activist->actions()->count();
}
}
public function getActivist($id)
{
$activist = Activist::with('actions')->whereHas('actions', function($q) {
$user = Sentry::getUser();
$q->where('client_id', $user->client_id);
})->find($id);
$activist->total = $activist->actions()->count();
}
I'm seeing the following:
On the /activists page, I'm correctly seeing only those activists who have taken an action related to my client_id, but also every action they've taken. Likewise, count() returns a full count of all the activists' actions.
On the /activists/{id} page, it correctly returns null if the activist hasn't taken any actions related to my client_id, but where they have, I again see all of their actions and a full count.
AFL. There's something blinding obvious I'm missing, right?
Thanks.
[edit] Updated to add:
Using the client_id filter on both with and whereHas rectifies the 'all actions appearing regardless' issue, but the count issue remains (and I'm not sure this is remotely the right way to improve this):
ActivistController.php
public function index()
{
$filter = function($q) {
$user = Sentry::getUser();
$q->where('client_id', $user->client_id);
};
$activists = Activist::with(array('actions' => $filter))
->whereHas('actions', $filter)
->get();
}
public function getActivist($id)
{
$filter = function($q) {
$user = Sentry::getUser();
$q->where('client_id', $user->client_id);
};
$activist = Activist::with(array('actions' => $filter))
->whereHas('actions', $filter)
->find($id);
}
I've solved this now, but for reference:
$activist->actions()->count()
This, obviously in hindsight, ignores any of the prior queries and simply counts data returned from the actions() method as defined in the activist model.
I should have provided an alternate method in the model that includes the appropriate where function, like so:
public function actionsClient($id)
{
return $this->hasMany('Action')->where('client_id', $id);
}
Meaning the count could then be invoked with:
$activist->total = $activist->actionsClient($id)->count();
for a single campaign and
foreach ($activists as $activist)
{
$activist->total = $activist->actionsClient($activist->id)->count();
}
on the index. I'd previously tried this, but as described here - How to access model hasMany Relation with where condition? - relations must be described in camelCase (actions_client > actionsClient).
In my usage this worked for me:
$clients = Profile::select('id', 'name')->orderBy('initial')->whereHas('type', function ($query) {
$query->where('slug', 'client');
})->office()->pluck('name', 'id');
You already have the instance of $activist eager loading their actions, meaning you already know the actions of the activist beacause they are already in the instance, so why call actions() again instead of just doing this:
$activist->actions->count()