Laravel paginate with only first result - laravel-5

i'm kinda new to Laravel so I hope the question is clear enough.
I have a table with Users and another table with Tasks.
In my User model I have the following :
public function tasks() {
return $this->hasMany('App\User' , 'id');
}
I can do the following to retrieve a single user from the DB
$users = \App\User::find(1)->tasks()->paginate();
but i get
{"current_page":1,"data":[{"id":1,"name":"Ed","email":"mail#weqweqeq.com","email_verified_at":null,"created_at":null,"updated_at":null,"tasks":[{"id":1,"name":"Ed","email":"mail#weqweqeq.com","email_verified_at":null,"created_at":null,"updated_at":null}]},{"id":2,"name":"Alyse","email":"mail#rxygewe.com","email_verified_at":null,"created_at":null,"updated_at":null,"tasks":[]}],"first_page_url":"http:\/\/127.0.0.1:8000?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/127.0.0.1:8000?page=1","next_page_url":null,"path":"http:\/\/127.0.0.1:8000","per_page":15,"prev_page_url":null,"to":2,"total":2}
I've also tried :
$users = \App\User::with(['tasks' => function($q) {
$q->first();
}])->paginate();
but the tasks property is empty
My question is how I can get all the users but only with first task and paginate to work?
Tasks table
1 id(Primary) bigint(20) UNSIGNED No None AUTO_INCREMENT
2 created_at timestamp Yes NULL
3 updated_at timestamp Yes NULL
4 task_name varchar(255) utf8mb4_unicode_ci No None
5 user_id(Index) bigint(20) UNSIGNED No None

Your model relationship is defined incorrectly. You have associated a User with many Users.
https://laravel.com/docs/master/eloquent-relationships#one-to-many
public function tasks() {
// a User ($this) has many Tasks
return $this->hasMany('App\Task');
}
Also, be careful when using ->first() as the order is not guaranteed unless specified.
$users = \App\User::with(['tasks' => function($q) {
// get the most recently created task
$q->latest()->first();
}])->paginate();

for another example
$getData = $User::where('code_transaction',$code)->first();
$pag = $getData->paginate(10);

Related

Get only one column from relation

I have found this: Get Specific Columns Using “With()” Function in Laravel Eloquent
but nothing from there did not help.
I have users table, columns: id , name , supplier_id. Table suppliers with columns: id, name.
When I call relation from Model or use eager constraints, relation is empty. When I comment(remove) constraint select(['id']) - results are present, but with all users fields.
$query = Supplier::with(['test_staff_id_only' => function ($query) {
//$query->where('id',8); // works only for testing https://laravel.com/docs/6.x/eloquent-relationships#constraining-eager-loads
// option 1
$query->select(['id']); // not working , no results in // "test_staff_id_only": []
// option 2
//$query->raw('select id from users'); // results with all fields from users table
}])->first();
return $query;
In Supplier model:
public function test_staff_id_only(){
return $this->hasMany(User::class,'supplier_id','id')
//option 3 - if enabled, no results in this relation
->select(['id']);// also tried: ->selectRaw('users.id as uid from users') and ->select('users.id')
}
How can I select only id from users?
in you relation remove select(['id'])
public function test_staff_id_only(){
return $this->hasMany(User::class,'supplier_id','id');
}
now in your code:
$query = Supplier::with(['test_staff_id_only:id,supplier_id'])->first();
There's a pretty simple answer actually. Define your relationship as:
public function users(){
return $this->hasMany(User::class, 'supplier_id', 'id');
}
Now, if you call Supplier::with('users')->get(), you'll get a list of all suppliers with their users, which is close, but a bit bloated. To limit the columns returned in the relationship, use the : modifier:
$suppliersWithUserIds = Supplier::with('users:id')->get();
Now, you will have a list of Supplier models, and each $supplier->users value will only contain the ID.

Issue while trying to search using whereBetween in Laravel Eloquent

I have 2 database tables in MySQL below.
Table - 1
CREATE TABLE `tblaccount` (
`account_id` mediumint(8) UNSIGNED NOT NULL,
`account_number` varchar(100)
)
ALTER TABLE `tblaccount`
ADD PRIMARY KEY (`account_id`);
Table - 2
CREATE TABLE `tblcollectoractions` (
`collector_action_id` mediumint(8) UNSIGNED NOT NULL,
`account_id` mediumint(8) UNSIGNED DEFAULT NULL,
`pay_date` date DEFAULT NULL
);
ALTER TABLE `tblcollectoractions`
ADD PRIMARY KEY (`collector_action_id`),
ADD KEY `tblcollectoractions_account_id_foreign` (`account_id`);
I have a query below. It joins records in both tables on the basis of account_id. It also filters those accounts in tblcollectoractions table where pay_date lies between start and end date.
Here is my Laravel Eloquent Query. AccountModel is related to tblaccount and ActionModel is related to tblcollectoractions.
$query = (new AccountModel())->newQuery();
$data->whereIn("account_id", function($query) use($inputs) {
$query->select('account_id')->from(with(new ActionModel)->getTable())
->whereBetween('pay_date', [$inputs["from_pay_date"], $inputs["to_pay_date"]]);
});
But, this shows me all the records from table tblcollectoractions. I meant, it does not filter on the basis of start and end date.
Am I missing anything?
This is the most Eloquent way to do this, checking if the $inputs variable is set
$data = AccountModel::query()
->with([
'actions' => function($query) use ($inputs) {
if ($inputs['from_pay_date']) {
$query->whereBetween('pay_date', [
$inputs['from_pay_date'],
$inputs['to_pay_date']
]);
}
}
])
->has('actions')
->get();
the models should look something like this:
AccountModel.php
class AccountModel extends Model
{
protected $guarded = ['id'];
public function actions()
{
return $this->hasMany(ActionModel::class, 'account_id', 'account_id');
}
}

Eloquent hasOne relationship return null

I have 2 models Admin and Subscription
Model Admin.php
public function subscription() {
return $this->hasOne('App\Subscription','admin_id','id');
}
Model Subscription.php
public function payer() {
return $this->belongsTo('App\Admin','admin_id','id');
}
When i try to get payer of the subscription it returns null.
I am getting a payer like this.
In Controller.php
$subscriptions=Subscription::all();
foreach ($subscriptions as $subscription) {
dd($subscription->payer);
}
Please give me a solution. I tried and change everything it's still not working.
This is my migrations
Subscription Table
id int(10) unsigned Auto Increment
subscription_type varchar(191) NULL
expiry_date timestamp NULL
status varchar(191) [required]
admin_id varchar(191)
created_at timestamp NULL
updated_at timestamp NULL
Admin Table
id int(10) unsigned Auto Increment
name varchar(191)
email varchar(191)
password varchar(191)
remember_token varchar(100) NULL
created_at timestamp NULL
updated_at timestamp NULL
Im not sure since you haven't showed your migration files but I think you might be setting the relation wrongly, you are specifying the same foreign. Also if primary key is named 'id' you don't need to specify it. So maybe this works out:
Model Admin
public function subscription()
{
// asumes foreign key is called admin_id
return $this->hasOne('App\Subscription');
}
Model Subscription
public function payer()
{
// asumes foreign key is called subscription_id
return $this->belongsTo('App\Admin');
}
Update, if you have your tables named as you are suggesting you won't need to specify any key because you are following laravel default naming conventions.
Laravel pitches a fit if you don't use a number as an id. You have to tell it if you use a string.
protected $keyType = 'string';
the method name you write for hasOne must have more than 3 chars.

Eloquent Relationships in laravel

i have three table as follows:
users:
id, fullname, phone ...
tasks:
id, user_id, title, description ...
tasks_state:
id, task_id, comment, rating, createa_at, updated_at
i am trying to use Relationships in laravel for order by updated_at in table tasks_state
Model tasks
public function taskstate()
{
return $this->hasOne(TaskState::class, 'task_id');
}
Model tasks_state
public function task()
{
return $this->belongsTo(Tasks::class, 'id', 'taks_id');
}
I want the data returned sorted by field updated_at in table tasks_state when i use:
Tasks:with('taskstate')->get();
Look forward to your help :(
Change your Task Model like this:
Model tasks
public function taskstate()
{
return $this->hasOne(TaskState::class, 'task_id')->orderBy('tasks_state.updated_at');
}
You can use query builder within with clause and order the task state by updated_at
Tasks:with([
'taskstate' => function($query){
$query->orderBy('updated_at', 'desc');}
])->get();
If you want to retrieve everytime with updated_at in desc order, you can reference to Stack Overflow: Laravel default orderBy

Laravel 5 eloquent: select specific column of relation

I have 2 models: Author and Post
In my Post model, I have an author function (One To Many (Inverse)):
public function author()
{
return $this->belongsTo('App\Author', 'author_id');
}
Now I want to export to Excel the following information:
id | title | author name
This is what I tried:
$posts = Post::with(array(
'author' => function ($query) {
$query->select('name');
}))->select('id', 'title')->get();
What I get is an empty author's name column.
What do I wrong?
Since Laravel 5.5 you can use eager loading retrieve multiple specific columns simply by using string
Post::with('author:id,name')->get()
Author::with('posts:id,author_id,title')->get()
Notice the id or foreign key (author_id) must included, or data will be null.
please try:
$posts = Post::with(['author' => function($query){
$query->select(['id','name']);
}])->get(['id','title', 'author_foreign_key_in_posts_table']);
Having that, you'll be able to get:
$posts->first()->author->name;
$posts->first()->id;
$posts->first()->title;
You may use iteration or whatever instead of first() for export.

Resources