How can I select linked objects from multiple parent objects in Laravel Eloquent - laravel

I would like to do something like this.
Location::where('city', '=', 'Chicago')->chef();
With these relationships:
class Location extends Eloquent {
protected $table = 'locations';
public function chef() {
return $this->belongsTo('Chef');
}
}
class Chef extends Eloquent {
protected $table = 'chefs';
public function location() {
return $this->hasMany('Location');
}
}

This should work:
class Location extends Eloquent {
protected $table = 'locations';
public function chefs() {
return $this->belongsTo('Chef');
}
public function getAllChefsByCity($city)
{
$this->with('chefs')->where('city', $city)->get();
}
}
Then in your code:
$array = $location->getAllChefsByCity('Chicago');

Related

Many to many Laravel issue models?

There are two models:
class Specialization extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = ['name', 'parentid'];
public function scopeActive($query)
{
return $query->where('status', true);
}
public function services()
{
return $this->hasMany(Service::class);
}
}
class Service extends Model
{
use HasFactory;
public function specializations()
{
return $this->belongsToMany(Specialization::class);
}
}
Each specialization has many services. I try to get them:
public function services(Specialization $specialization)
{
$specializations = $specialization->services()->get();
return response()->json($specializations);
}
As result I got this error:
"message": "PDO: SQLSTATE[42703]: Undefined column: 7 ОШИБКА: столбец services.specialization_id не существует\nLINE 1: select * from \"services\" where \"services\".\"specialization_id...\n ^ (SQL: select * from \"services\" where \"services\".\"specialization_id\" = 1 and \"services\".\"specialization_id\" is not null)"
}
Why is field specialization_id looking in services table instead third table?
You should have belongsToMany on both relationships.
class Specialization extends Model
{
public function services()
{
return $this->belongsToMany(Service::class);
}
}
class Service extends Model
{
use HasFactory;
public function specializations()
{
return $this->belongsToMany(Specialization::class);
}
}
The default pivot table name will be service_specialization I think. If you want to change it, pass it as the 2nd parameter.

How to display owner of a post in laravel admin list display?

public function index()
{
$query = Activity::orderBy('id','DESC')->with('provinces');
if(!Auth::user()->hasRole('Administer')){
$query=$query->where('province_id', Auth::user()->id);
}
$activities = $query->latest()->get();
return view('activity.index',compact('activities'));
}
How to display owner of a post in laravel admin list display?
My User Model
class User extends Authenticatable implements HasMedia
{
public function activities()
{
return $this->hasMany(Activity::class);
}
}
My Activity Model:
class Activity extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function provinces()
{
return $this->belongsToMany(Province::class);
}
}
My province Model
class Province extends Model
{
protected $fillable = [ 'title', 'post_id'];
public function activities()
{
return $this->belongsToMany(Activity::class);
}
public function user()
{
return $this->belongsToMany(User::class);
}
}
I want to show the content to the user by province.
And also the admin can see all the content.
please help me i am new in laravel
Based on your comment, you should change your province conditions to:
if (!Auth::user()->hasRole('Administer')) {
$query = $query->where('province_id', Auth::user()->province_id);
}
You have defined that each activity belongs to an user. So can access owner of each activity like this:
$activity->user->name;
And if your activity belongs to a province, you should define your relation in this way:
class Activity extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function province()
{
return $this->belongsTo(Province::class);
}
}
Also for your Province model:
class Province extends Model
{
protected $fillable = [ 'title', 'post_id'];
public function activities()
{
return $this->hasMany(Activity::class);
}
public function users()
{
return $this->hasMany(User::class);
}
}
And this is best practice to use eager loading for fetching related records. It will look like this one:
$query = Activity::with(['user', 'province'])->orderBy('id','DESC');
Also another hint: try to use better variable names. You can use $activities instead of $query.

Call to undefined relationship on model

We have the following class using $with:
class CargaHorasEmpleado extends Model
{
protected $table = "empleados_horas";
protected $with = ["tipoTarea", "proyecto", "empleado", "empleadoQueHizoLaCarga"];
public function tipoTarea()
{
return $this->belongsTo('App\TipoTarea', 'id_tipo_tarea', 'id')->withTrashed();
}
public function empleado()
{
return $this->belongsTo('App\Empleado', 'id_empleado', 'id')->withTrashed();
}
public function empleadoQueHizoLaCarga()
{
return $this->belongsTo('App\Empleado', 'id_empleado_cargo_hs', 'id')->withTrashed();
}
public function proyecto()
{
return $this->belongsTo('App\Proyecto', 'id_proyecto', 'id')->withTrashed();
}
}
This is the class TipoTarea
namespace App;
use Illuminate\Database\Eloquent\Model;
class TipoTarea extends Model
{
protected $table = 'tipos_tareas';
public $timestamps = false;
protected $fillable = [
'titulo', 'descripcion'
];
}
Thep page throws the error: "Call to undefined relationship [tipoTarea] on model [App\CargaHorasEmpleado]". That's the only relationship that's not working. The others are fine. What's wrong?
Well, isn't the relationship called "tipoTarea"? You wrote "tiposTarea"
The problem was that my class "TipoTarea" didn't use softdeletes. So the error was in using the "WithTrashed" method. The correct way is:
public function tipoTarea()
{
return $this->belongsTo('App\TipoTarea', 'id_tipo_tarea', 'id');
}

Laravel5.3:How to use pluck in relationship for bindign Form::select element?

This is my model:
class Positions extends Model implements Repository
{
protected $fillable = ['index_id', 'title', 'description'];
public function index()
{
return $this->belongsTo('TEST\Indices', 'index_id');
}
public function getById($id)
{
return $this->with('index')->find($id);
}
}
how to use pluck() in getById() function for listing index relationship?
You can do it like this :
return $this->with('index')->find($id)->pluck('index.indexField');

Model Event not working

I have the following model:
class ProjectTwitterStatus extends Eloquent {
protected $table = 'project_twitter_statuses';
protected $softDelete = true;
protected $guarded = array('id');
public static function boot()
{
parent::boot();
ProjectTwitterStatus::deleting(function($projectTwitterStatus)
{
$projectTwitterStatus->deleted_by = Auth::user()->id;
});
}
public function twitterStatus() {
return $this->belongsTo('TwitterStatus');
}
public function twitterRetweet() {
return $this->belongsTo('TwitterRetweet','twitter_status_id','twitter_status_id');
}
public function project() {
return $this->belongsTo('Project');
}
}
Somewhere in my app an item is deleted using one of the following statements:
ProjectTwitterStatus::find($id)->delete();
ProjectTwitterStatus::whereIn('twitter_status_id', $twitterStatusIds)->delete();
I can see in the database the item had been (soft) deleted. But the deleted_by column is not filled.
Does anyone know what I am doing wrong?
Try using Late Static Binding, like following-
class ProjectTwitterStatus extends Eloquent {
public static function boot ()
{
parent::boot();
static::deleting(function($projectTwitterStatus)
{
$projectTwitterStatus->deleted_by = Auth::user()->id;
});
}
}

Resources