My code is:
App\Models\Client.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
protected $guarded = ['id'];
public function transactions()
{
return $this->hasMany('App\Models\Transaction','clients_id');
}
}
App\Models\Transaction.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
protected $guarded = ['id'];
public function clients()
{
return $this->belongsTo('App\Models\Client','clients_id');
}
}
In controller i tried
use App\Models\Client;
use App\Models\Transaction;
Client::with('transactions')->orderBy('id', 'desc')->get();
but it's not working as expected
Thanks in Advance
To get all clients in desc order with your transactions using
$clients = Client::with('transactions')->orderBy('id', 'desc')->get();
returns all clients which has 1 or more transactions. By your mention in above comments "It returns all of the clients despite having zero transaction records" below query will not do that
$clients = Client::has('transactions')->orderBy('id', 'desc')->get();
or
$clients = Client::has('transactions', '>=', 0)->orderBy('id', 'desc')->get(); // you can add any number in place of zero
It is all given in the docs
Related
I am using Laravel 8.X and eloquent to develop a web app.
I have a pivot table 'portal_event_users'
I am trying to add a belongsToMany relationship to the portal_users in the model of portal_event_users table.
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class EventUser extends Model
{
use HasFactory;
protected $table = 'portal_event_users';
public function users()
{
return $this->belongsToMany(User::class);
}
public function events()
{
return $this->belongsToMany(Event::class);
}
}
I have the following statements in the controller
$eventusersobj = \App\Models\EventUser::select('*')
->where('event_id', '=', $event_id)
->get();
$response = $eventusersobj->users->keyBy('id');
It is returning the following error
Property [users] does not exist on this collection instance.
Can someone please advice on how can i change this error?
Thanks in advance
As it returns a collection, you can use pluck()
$eventusersobj->pluck('users')->each(function($user){
$user->keyBy('id');
})
I want to to retrieve all buyers for a specific saller.When I remove pluck and others methods chaining after get method it's working. But is not exact thing that I want. How Can I solve this provlem?
(source: licdn.com)
<?php
namespace App\Http\Controllers\Seller;
use App\Http\Controllers\ApiController;
use App\Seller;
use Illuminate\Http\Request;
class SellerBuyerController extends ApiController
{
public function index(Seller $seller)
{
$buyers = $seller->products()
->whereHas('transactions')
->with('transactions.buyer')
->get()->pluck('transactions')
->collapse()->pluck('buyer')
->unique('id')
->values();
return $this->showAll($buyers);
}
protected function showAll(Collection $collection, $code = 200)
{
return $this->successResponse($collection, $code);
}
protected function successResponse($data, $code)
{
return response()->json($data, $code);
}
}
Seller model hasMany relation to products
<?php
namespace App;
use App\Scopes\SellerScope;
class Seller extends User
{
public function products()
{
return $this->hasMany(Product::class);
}
}
Product Model hasMany relation to transactions
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $fillable = [
'name', 'description', 'quantity', 'status', 'image', 'seller_id',
];
public function transactions()
{
return $this->hasMany(Transaction::class);
}
}
Transaction Model and relation to buyer
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Transaction extends Model
{
use SoftDeletes;
protected $fillable = [
'quantity', 'buyer_id', 'product_id'
];
public function buyer()
{
return $this->belongsTo(Buyer::class);
}
}
You are missing an import at the top:
use Illuminate\Support\Collection;
otherwise it assumes Illuminate\Database\Eloquent\Collection is to be used.
And values() obviously returns the support collection, not an eloquent one.
If you have a relationship from Buyer to Transaction you can go at this from the other direction to get buyers. You also need to make sure there is a relationship from Product to Seller (make sure you have the inverse of every relationship setup)
Buyer::whereHas('transactions.products.seller', function ($query) use ($seller) {
$query->where('id', $seller->id); // might have to be a more specific key name
})->get();
You would end up with a Eloquent Collection of Buyers who have transactions including products from a particular seller.
you should put use Illuminate\Support\Collection; in folder traits over apiResponser.php
I have two Models (Color and ColorFamily Table).I would like to join two table.When I join Second Table (ColorFamily),its shows an error message "Invalid Object Name ColorFamily".If I use to Join First Table then its shows an error message "Invalid Object Name Color".
Note:-
If I use Individual Query (Select Query) without join ,then the records is showing,that means both the tables are available...
I have check with google but can not find the solution.....
Color Models:-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Color extends Model
{
protected $primaryKey = 'ColorId';
protected $table = 'Common_Ref_Color';
public $timestamps = false;
}
ColorFamily Models:-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ColorFamily extends Model
{
protected $primaryKey = 'ColorFamilyId';
protected $table = 'Common_Ref_ColorFamily';
public $timestamps = false;
}
Controller:-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use App\Models\ColorFamily;
use App\Models\Color;
class ColorController extends Controller
{
public function Index()
{
$Data = Color::select ('ColorId','ColorName','ColorCode','ColorShortCode')
->join('ColorFamily','ColorFamilyId','=','Color.ColorFamilyId')
->get();
return $Data;
}
}
Can you try the following code:
class ColorController extends Controller {
public function Index()
{
$Data = DB::table('Color')
->select ('ColorId','ColorName','ColorCode','ColorShortCode')
->join('ColorFamily','ColorFamily.ColorFamilyId','=','Color.ColorFamilyId')
->get();
return $Data;
}
}
I think that you need to add joined table name inside join
('ColorFamily.ColorFamilyId','=','Color.ColorFamilyId')
I'm learning VueJS and trying to develop a forum system
I am trying to get the latest post from the threads relationship per forum in my forum model.
This is my Forum Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forum extends Model
{
public $table = 'forums';
public $timestamps = false;
public function threads() {
return $this->hasMany('App\Thread')->orderBy('id', 'DESC');
}
public function getFirstThread() {
return $this->threads()->first();
}
}
So I thought maybe this would work but it didn't
Forum::with('getFirstThread')->get();
Any idea's how I can achieve this without having to loop through everything and getting first thread for every result?
TLDR: Trying to get the latest Thread per Forum without having to loop through all forums.
You can $append the method results by using getMethodNameAttribute()
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forum extends Model
{
public $table = 'forums';
public $timestamps = false;
protected $appends = ['firstthread'];
public function threads() {
return $this->hasMany('App\Thread')->orderBy('id', 'DESC');
}
public function getFirstThreadAttribute() {
return $this->threads()->first();
}
}
You could define another mapping as hasOne in your model to get latest thread per forum, Call latest('id') on your mapping and pass id as a column to sort
public function latest_threads() {
return $this->hasOne('App\Thread')->latest('id');
}
Then you can easily eager load your relationship as
Forum::with('latest_threads')->get();
I am using Laravel 5.2.
I have a model as below:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
class ZoomMeeting extends BaseModel {
public $timestamps=true;
protected $table = 'zoom_meetings';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = ['user_id', 'uuid', 'meeting_id', 'host_id', 'topic', 'status', 'type', 'start_url', 'join_url', 'created_at'];
public function users() {
return $this->belongsTo('App\Models\User');
}
}
And the base model is as below:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Auth;
use Carbon\Carbon;
class BaseModel extends Model {
public $timestamps = false;
protected static function boot()
{
//parent::boot();
static::creating(function($model) {
if(empty($model->created_at))
{
$model->created_at = date('Y-m-d H:i:s');
}
return true;
});
static::updating(function($model) {
$model->updated_at = date('Y-m-d H:i:s');
return true;
});
}
}
I am using softdeletetrait in ZoomMeeting model, and soft deleting is working fine.
However, if I fetch records from the same model using eloquent, it returns the soft deleted records too. I am using code below to get the records:
$record = ZoomMeeting::where("user_id", $user_id)->where("meeting_id", $meeting_id)->orderBy("id", "DESC")->first();
The eloquent is building the query as:
select * from `zoom_meetings` where `user_id` = 3 and `meeting_id` = 707070707 order by `id` desc limit 1
See, there is no deleted at is null set in where statement. It is not preventing the deleted records.
I am not sure where am I making mistake?
It looks like you are overriding the boot method, but you aren't ever actually calling the parent boot method (it's commented out), so the trait is never getting initialized correctly. I believe that also means the data you have been deleting is actually being deleted from the database.
Is there a reason you need to override the boot method? What you are adding is already done handled by the framework, so it doesn't appear to be necessary.