Multiple Where Clause in Eloquent & Laravel - laravel-5

Trying to do a multiple select statement with eloquent.
used the Blog::where()
... function, and included an array in it.
$matchThese = ['title' => post('title'), 'slug' => post('slug')];
return Blog::where($matchThese)->get();
When tested it returns an empty value even for matching inputs, database table names correctly written
Model extends October CMS Model, so all eloquent methods in laravel are include. Blog Model Below
<?php namespace Andre\Blogroutes\Models;
use Model;
use ModelNotFoundException;
class Blog extends Model
{
use \October\Rain\Database\Traits\Validation;
public $table = 'blog';
}

Both of the following queries are exactly the same:
$matchThese = ['title' => post('title'), 'slug' => post('slug')];
return Blog::where($matchThese)->get();
and
return DB::table('blog')->where('title', '=',post('title'))->where('slug','=', post('slug'))->get();
if one worked and others didn't that means your Blog model is not actually targetting the right table blog. You should add the following line to you Blog model and see if the old query works:
protected $table = 'blog';
Also inside your controller, do not forget to add:
use App\Blog;
on top of it. Give the old query a roll and see if that works.

Was able to fix this:
DB::table('blog')->where('title', '=',post('title'))->where('slug','=', post('slug'))->get();

The $table variable must be protected not public
public $table = 'andre_blog';
to
protected $table = 'andre_blog';

Related

Laravel builder - specify a connection on the builder object

I have an eloquent query builder in Laravel
$builder = Model::orderBy('created_at', 'DESC');
I want to specify a connection to use, because I have a separate db for some data - let's call it 'archive' for example.
Now, I know I can do it statically, like $builder = Model::connection('archive'); [edit] ::on('archive'); apparently
But if I already have the $builder object, and can't use the static function, how can I do it on the builder object?
I've tried
$builder->connection('archive');
$builder->onConnection('archive');
$builder->setConnection('archive');
And these are all failing for me.
There are two solutions.
Define in class
class MyModel extends Model {
protected $connection= 'archive';
protected $table = 'table_name';
}
In a query
(new MyModel())->on('archive')->get();

laravel eloquent migrations

In laravel eloquent relationship, is it still necessary to make migration even though there's an existing database? beginners here.
I create a one-to-one eloquent relationship inside my model to get the specific column from another table's record and fetch to the datatable, but it did not work.
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Directorystatus extends Model
{
use HasFactory;
protected $table = 'user_status';
protected $fillable = ['status_id' , 'status_xtitle'];
public function userbasic() {
return $this->belongsTo(directorybasic::class,'user_xusern','status_xuser');
}
}
class Directoryuser extends Model
{
use HasFactory;
protected $table = 'user_basic';
protected $primaryKey = 'user_id';
protected $fillable = ['user_id' , 'user_xusern' , 'user_xfirtname' ,'user_xmiddlename','user_xlastname'];
public function userstatus() {
return $this->hasOne(directorystatus::class,'user_xusern','status_xuser');
}
}
No. Migrations are not necessary. Defining relationships on both sides is also not necessary, if you don't need them both. (You can have only belongsTo, without having hasOne or hasMany in the opposite model.)
First, make sure you are using the right object (Directorystatus::class / Directoryuser:class - I see they're not capitalized in your code). The next param is the foreign key, meaning the column which points to a model's primary key. The third param is optional and is used only if the primary key is not id.
For example if you have a column status_xuser in the table user_status, which contains a user_id from user_basic table, you should define it like this:
public function userbasic() {
return $this->belongsTo(Directoryuser::class,'status_xuser','user_id');
}
And in order to use this relationship, when you retrieve a model from the db, for example, you should call on it the same way your relationship function is named.
$status = Directorystatus::find(1);
$user = $status->userbasic();
I would also suggest you name your classes in camelCase, because it's the accepted practice (in Laravel especially).

Laravel getAttribute() on eloquent?

so i just wondered, if something like this is possible, since my code does not work.
protected $appends = ['position_name'];
public function getPositionNameAttribute()
{
return $this->belongsTo('App\EmployeePosition', 'employee_position_id')->name;
}
Can I append the name of Eloquen relationship model?
edit: so far, i am using this:
foreach ($employees as $e) {
$e->position_name = $e->position->name;
}
So, I needed to use the relation defined before.
protected $appends = ['position_name'];
public function position()
{
return $this->belongsTo('App\EmployeePosition', 'employee_position_id');
}
public function getPositionNameAttribute()
{
return $this->position->name;
}
Based on your comments i'd suggest to use the laravel default solution for your problems API resrouces
eg
class EmployeeResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'position_name' => $this->position->name,
];
}
}
note: using the with as other people suggested to preload information can increase performance by reducing the amount of queries, if you are returning a collection of employees.
Creating an accessor that looks up a value in another model and appending this field by using $appends is bad practice and will lead to n+1 queries whenever you fetch your Employee model. You should avoid doing this and just use $employee->position->name.
You should also make sure to use Employee::with('position') when you need to show the position name, so that the position model is fetched in a single query.
If the position name is something that you need in all your Employee queries, then you can set the Employee to always eager load the position by defining the following inside your Employee model:
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = ['position'];
I think you can just create a model with position names and reference it to the position id in the other mode by using eloquent relationships.

Can eloquent ignore irrelevant data in Laravel 5.7

This is basically the same question as this here from 2013. Except the answer doesn't work for me.
I have a Model App\Post:
class Post extends Model
{
protected $fillable = ['title'];
// This Model doesn't contain an 'authorname' field
public function author()
{
return $this->belongsTo('App\Author');
}
}
and a Model App\Author:
class Author extends Model
{
protected $fillable = ['name'];
public function posts()
{
return $this->hasMany('App\Post');
}
}
And an array I want to save to that Model:
$posts = [
['title'=>'one post', 'authorname' => 'Mickey'],
['title'=>'another post', 'authorname' => 'Minny'],
];
foreach($posts as $post){
$authorModel=App\Author::firstOrCreate(['name'=>$post['authorname']]);
App\Post::create($post)->author()->associate($authorModel)->save();
}
According to this question, that should work, but I get an
SQL error 42522: Column not found: 1054 Unknown column 'authorname' in 'field list'
which suggests Laravel forwards the whole array to mySQL. Is there a way to make this work without unsetting the authorname key?
Obviously this is a simpified version of what I want to do and keeping track of what to unset seems unnecessary - as would be assigning all array keys to their respective database fields manually.
The only idea I have here is that you run this code in DatabaseSeeder (which automatically unguards models) or you somewhere manually call Eloquent::unguard() (or code similar to this). This would explain why any other fields are used when creating model no matter of $fillable property.

Laravel saving hasMany relationship

I'm using Laravel & Ardent and having issues saving through the hasMany relationship.
I have two classes.
Workorder:
protected $table = 'workorder';
protected $primaryKey = 'workorder_id';
public static $relationsData = [
'dates' => array(self::HAS_MANY, 'App\WorkOrderDate', 'foreignKey' => 'workorder_id'),
];
WorkOrderDate:
protected $table = 'workorder_date';
protected $primaryKey = 'date_id';
public static $relationsData = array(
'workorder' => array(self::BELONGS_TO, 'App\WorkOrder')
);
after saving my Workorder (which works fine), I'm trying to save a collection of Date models by executing:
$workorder->dates()->saveMany($myDateCollection->all());
But it's not running the date insert, and it's not giving me any errors. I turned on query logging and it looks like Laravel is trying to run an update instead of an insert. Do I have my relationship defined incorrectly here?
I was hydrating my date collection from user input, and when you hydrate a model, Laravel assumes the model exists already. Turns out this is not what I mean to do.
More detail here:
https://github.com/laravel/framework/issues/9360

Resources