how I can append atribute in model, that calculated by sql?
I have try this:
protected $appends = ['comment_qty'];
public function getCommentQtyAttribute()
{
return DB::raw("(select 1) as comment_qty");
}
It's not working
Define a mutator method setCommentQtyAttribute on your model, where comment_qty is your custom column name.
Look at the below...
class Comment extends Eloquent {
protected $table = 'comments';
protected $appends = array('comment_qty');
public function setCommentQtyAttribute()
{
return DB::raw("(select 1) as field");
}
}
For more information : Accessors and mutators
Another yet solution, add to model.
protected static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
static::addGlobalScope('any', function (Builder $builder) {
$builder->select(['*', DB::raw("'any' as any")]);
});
}
Related
I want to use data from the parent model to run the saving() function in the child model
Previously, I inserted a computed data to the table in model "Loan" but now I need to insert it into a child model "InterestAmount"
Loan.php
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $fillable ['amount','interest','status','duration','member_id','loan_type_id','interest_type_id','loan_payment_type_id'];
//protected $appends = 'interest_amount
protected static function boot()
{
parent::boot();
static::saving(function($model) {
$model->interest_amount = ($model->amount/100 )* $model->interest;
});
}
public function interest_amount()
{
return $this->hasMany(InterestAmount::class,'loan_id','id');
}
}
I want to remove the saving function from Loan.php and use as below.
Interest.php
use Illuminate\Database\Eloquent\Model;
class InterestAmount extends Model
{
public function loan()
{
$this->belongsTo(Loan::class,'loan_id','id');
}
protected static function boot()
{
parent::boot();
static::saving(function($model) {
$model->interest_amount = ($model->amount/100 )* $model->interest;
});
}
}
How do I fetch "amount" and "interest" in this function?
The $model variable inside InterestAmount model refers to an InterestAmount object :
static::saving(function($model){
$model->interest_amount = ($model->loan->amount/100 )* $model->loan->interest;
});
Then you need to get the related loan using your relationship method loan() then get the properties amount/interest.
NOTE: As #namelivia's comment says you're missing the return in the loan() method:
public function loan()
{
return $this->belongsTo(Loan::class,'loan_id','id');
}
I like to list all MovimentoProdutoUnidade that movimento_id = 3 using the hasMany function.
My Model Movimento:
use Illuminate\Database\Eloquent\Model;
use App\Unidade;
class Movimento extends Model
{
protected $fillable = [
"movimento", "descricao", "requisitante", "despachante", "data", "unidade_ori_id", "unidade_des_id"
];
protected $table = "movimentos";
public function movimentoProdutoUnidade(){
return $this->hasMany('App\MovimentoProdutoUnidade', 'movimento_id');
}
}
My Model MovimentoProdutoUnidade
use Illuminate\Database\Eloquent\Model;
use App\Movimento;
class MovimentoProdutoUnidade extends Model
{
protected $fillable = [
"movimento_id", "unidadeProduto_id"
];
protected $table = "movimento_produtounidades";
public function movimento(){
return $this->belongsTo('App\Movimento', 'movimento_id');
}
}
My Controller:
public function licitacao(Request $request){
$movimentos = Movimento::where('unidade_ori_id', 3)->movimentoProdutoUnidade;
dd($movimentos);
//return view('relatorios.licitacao', compact('movimentos'));
}
The dd fuction return
Undefined property: Illuminate\Database\Eloquent\Builder::$movimentoProdutoUnidade
Your error is because you're not calling first() on the query builder object, so you have an instance of Builder (which does not have a $movimentoProdutoUnidade property) instead of a Movimento model:
$movimento = Movimento::where('unidade_ori_id', 3)->first();
$movimento_produto_unidade = $movimento->movimentoProdutoUnidade;
However, if you want all MovimentoProdutoUnidade, try thinking "backwards":
$movimento_produto_unidade = MovimentoProdutoUnidade::whereHas('movimento', function ($query) {
return $query->where('unidade_ori_id', 3);
})
->get();
As stated in the comment i made, try using first function like this:
Movimento::where('unidade_ori_id', 3)->first()->movimentoProdutoUnidade;
Remember always after the condition use get(), first() or find() functions to pull the data from the database.
Take a look to this link
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;
class Event extends Model
{
protected $table = 'events';
public $timestamps = true;
use Searchable;
use SoftDeletes;
protected $dates = ['deleted_at'];
public function entities()
{
return $this->belongsTo('App\Entity', 'entity_id');
}
public function users()
{
return $this->belongsTo('App\User', 'id');
}
public function events()
{
return $this->belongsTo('App\DirtyEvent', 'id');
}
public function toSearchableArray()
{
$data = $this->toArray();
$data['entities'] = $this->entities->toArray();
return $data;
}
}
This is my model for Event, as you can see I am using toSearchableArray which is Laravel scout function to import 'relations' to algolia. However the problem is that sometimes it is empty. So for example
event id 1 has entity_id 1
but in another example
event id 2 has entity_id = null
How can I modify this function to check if the entities() relation is not empty before putting it into array?
if i understand u correctly this should help. if the relationship does not exist return an empty array and scout won't update the index
public function toSearchableArray()
{
if(is_null($this->entities)){
return [];
}
$this->entities
return $this->toArray();
}
please update foreign_key in relation as this
user_id as foreign_key instead of id
event_id as foreign_key instead of id
public function users()
{
return $this->belongsTo('App\User', 'user_id');
}
public function events()
{
return $this->belongsTo('App\DirtyEvent', 'event_id');
}
I think if load the relation before the toArray().
public function toSearchableArray()
{
$this->entities;
return $this->toArray();
}
How do I call the relational data in the statement below using a with statement.
$suppliers = Supplier::with('user')->lists('user.company', 'user.id'); // doesn't work
class Supplier extends Model
{
protected $table = "suppliers";
protected $fillable = ['email'];
public function user() {
return $this->belongsTo('App\User', 'email', 'email');
}
}
You achieve your goal using the pluck method:
Supplier::with('user')->get()->pluck ('user.company', 'user.id');
The get method returns a Collection, then you can use its methods.
I want to populate Every CustomerEvent with the Customer related to the CustomerEvent.
When I Loop through the object and call to $customerevent->customer foreach object I can get the customer related to that event but Can I populate the all objects in the main object without looping through every single event ?
I want to do something like this:
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
Here my code:
Table 1: "events"
id, customer_id
Model for Table 1 "CustomerEvent":
<?php
class CustomerEvent extends Eloquent{
protected $guarded = ['id'];
public $table = "event";
protected $softDelete = true;
public function scopeTypeOne($query)
{
$followUps = $query->where('type_id', '=', '1');
}
public function Customers()
{
return $this->belongsTo('Customer', 'customer_id');
}
}
Table 2: "customers"
id
Model for Table 2 "Customers":
<?php class Customer extends BaseModel{
protected $guarded = ['id'];
}
EventController:
public function index()
{
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
dd($customersWithTypeOne);
}
From you database scheme I see customer has many events, so I would recommend to define this relationship in you Customer model.
class Customer extends BaseModel{
protected $guarded = ['id'];
public function events()
{
return $this->hasMany('CustomerEvent', 'customer_id');
}
}
Then you will be able to query customers with events:
$customersWithTypeOne = Customer::whereHas('events', function($query){
$query->where('type_id', 1);
})->get()
Maybe Ardent can help you: https://github.com/laravelbook/ardent
It's an extension for Eloquent models and very popular.