How to choose the fields from a associated model at find - cakephp-3.0

Before I had this:
//ArticlesController::index
$articles = $this->Articles->find('all', [
'contain' => ['Comments']
]);
So I set the fields key:
//ArticlesController::index
$articles = $this->Articles->find('all', [
'fields' => ['title', 'text],
'contain' => ['Comments']
]);
Since I set the fields key the result of the find is not bringing the comments anymore.

$articles = $this->Articles->find('all')
->select(['fields_you_want_from_Articles'])
->contain(['Comments' => function($q) {
return $q
->select(['fields_you_want_from_Comments']);
}]);

Related

Retrieve only necessary data

Here is my store function
public function store(Request $request)
{
$post = new Post();
$post->author()->associate(auth()->user());
$post->fill($request->all());
$post->save();
return response()->json($post);
}
As a response i get:
I don't want all the data so I tried to take only the data I have defined like this:
$post = $post->only([
'id',
'title',
'content',
'published_at',
'author'
]);
And response now is:
Much better, but not completely. I can not define post author data in this way.
The only way is by creating a creepy relationship where you select only necessary data or like this:
$post = [
'id' => $post->id,
'title' => $post->title,
'content' => $post->content,
'published_at' => $post->published_at->toDateTimeString(),
'author' => [
'id' => $post->author->id,
'name' => $post->author->name,
'email' => $post->author->email,
]
];
So my question is... maybe there is more elegant way to achieve this.
Thank you very much!
The simplest way would probably be to just use only with the author as well:
return $post->only('id', 'title', 'content') + [
'author' => $post->author->only('id', 'name', 'email'),
];
If it was going to get any more complicated or reused somewhere else then I would suggest using something like Eloquent Resources
I would add a function to your Post model
public function jsonOutput()
{
$array['id'] = $this->id;
$array['title'] = $this->title;
$array['content'] = $this->content;
$array['author'] = [
'id' => $this->author->id,
'name' => $this->author->id
];
return $array;
}
and then call it like this
return response()->json($post->jsonOutput());

Yajra DataTable search bar is not working

I have used Left Join Query in file called "directoryDataTable.php. Now the problem is that Yajra DataTable search bar is not working. Its neither giving any error nor the search result.
My DataTable query function is al follows.
public function query()
{
$id = \Illuminate\Support\Facades\Auth::user()->id;
$directories = DB::table('directories')
->leftjoin('claimed', 'directories.id', '=','claimed.dir_id')
->select('directories.*')
->where('directories.user_id',$id)
->where('paymentStatus','1')
->whereNull('directories.deleted_at')
->orWhere('claimed.claimed_by',$id);
return $this->applyScopes($directories);
}
Please Help
Changed the query to,
public function query()
{
$id = \Illuminate\Support\Facades\Auth::user()->id;
$directories = DB::table('directories')
->leftjoin('claimed', 'directories.id', '=','claimed.dir_id')
->select('directories.*')
->where(function ($query) {
$query->where('directories.user_id',\Illuminate\Support\Facades\Auth::user()->id)
->orWhere('claimed.claimed_by',\Illuminate\Support\Facades\Auth::user()->id);
})
->where('paymentStatus','1')
->whereNull('directories.deleted_at')
;
return $this->applyScopes($directories);
}
and in get columns function, replace ['name' => 'YourTableName.ColumnName','data' => 'YourColumnName'] Like this.
private function getColumns()
{
return [
'dir_name' => ['name' => 'directories.dir_name', 'data' => 'dir_name'],
'phone_number' => ['name' => 'directories.phone_number', 'data' => 'phone_number'],
'address' => ['name' => 'directories.address', 'data' => 'address'],
'features' => ['name' => 'directories.features', 'data' => 'features', ],
'Status' => ['name' => 'directories.Status', 'data' => 'Status','searchable'=>false ],
'Subscription' => ['name' => 'directories.Subscription', 'data' => 'Subscription','searchable'=>false ]
];
}

conditions doesn't work on hasMany association using contain in cakephp 3

I am trying to search on several conditions on Users Model and Addresses Model. Here Addresses Model are associated with Users Model in hasMany relation. Any condition on Users Model working fine but not working in Addresses Model. Here is my code snippet.
$this->hasMany('Addresses', [
'foreignKey' => 'user_id',
'joinType' => 'LEFT'
]);
$this->belongsTo('Users', [
'foreignKey' => 'user_id'
]);
$options = array();
$status = $this->request->getQuery('status');
$options = array_merge(array('Users.status' => $status), $options);
$profile = array();
$phone = $this->request->getQuery('phone');
$profile = array_merge(array('Addresses.phone' => $phone), $profile);
$addressArr = array('Addresses.user_id', 'Addresses.mobile', 'Addresses.phone', 'Addresses.country_id', 'Addresses.state_id', 'Addresses.city', 'Addresses.zipcode', 'Addresses.address_line1');
$uses = $this->find('all')
->select(['Users.id', 'Users.user_type_id', 'Users.first_name', 'Users.last_name', 'Users.email', 'Users.image', 'Users.status', 'Users.social_type'])
->contain([
'Addresses' => function ($q) use ($addressArr, $profile) {
return $q->select($addressArr)->where($profile);
}
])
->where($options)
->offset($offset)
->limit($limit)
->toArray();
return $uses;

order not working with sortWhitelist

Using CakePHP 3.5.3
Hi,
The below code works works as it should and displays the result set and orders it by the due_date asc.
public $paginate = [
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
public function index()
{
$session = $this->request->session();
// Declare client id 1
$cidOne = null;
$cidOne = $session->read('Cid.one');
// NOTE* DON'T USE ORDER HERE BECAUSE THE SORTS WILL NOT WORK
$query = $this->Activities->find('all')
->where(['cid_1' => $cidOne])
->andWhere(['status' => 1]);
// Send the query to the view.
$this->set('activities', $this->paginate($query));
}
But when I add sortWhitelist as below the initial page load is not sorted by the due_date and no sort arrow is displayed.
public $paginate = [
'sortWhitelist' => [
'due_date', 'related_to', 'subject', 'post_code', 'type', 'priority'
],
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
Thanks for any help. Z.
There must be consistency between the sortWhitelist array, the order array and the paginator link
so if your field is Activities.due_date your code becomes:
public $paginate = [
'sortWhitelist' => [
'Activities.due_date', 'related_to', 'subject', 'post_code', 'type', 'priority'
],
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
and in your view
<?= $this->Paginator->sort('Activities.due_date', __('Due Date')) ?>
If there is no ambiguity in the fields names you can omit the Model name and simply use due_date as column name

Insert or update in laravel?

What would be the best way to set this query? i can't seem to find any documentation on an actual insert or update that works, I'm hoping to do it via the Eloquent model but can't seem to get it working
any help would be appreciated.
DB::table('questions')->insert([
'marital_status' => $request->marital_status,
'job_title' => $request->job_Title,
'industry' => $request->industry,
'occupation' => $request->occupation,
'paye' => $request->paye,
'self_employed' => $request->self_employed,
'child_benefit' => $request->child_benefit,
'work_home' => $request->work_home,
'own_transport' => $request->own_transport,
'company_vehicle' => $request->company_vehicle,
'annual_income' => $request->annual_income,
'pay_memberships' => $request->pay_memberships,
'income_benefits' => $request->income_benefits,
'printer' => $request->printer,
'contact' => $request->contact,
'share' => $request->share,
'terms' => $request->terms,
'user_id' => $user
]);
here is my Model for Questions
<?php
namespace App;
class Questions extends Model
{
protected $fillable = [
'marital_status',
'job_title',
'industry',
'occupation',
'paye',
'self_employed',
'child_benefit',
'work_home',
'own_transport',
'company_vehicle',
'annual_income',
'pay_memberships',
'income_benefits',
'printer',
'contact',
'share',
'terms',
'user_id'
];
public function users(){
return $this->hasOne('App\User');
}
}
Use Eloquent with mass assignment:
Question::updateOrCreate($request->all()->put('user_id', $user));
Or:
$question = Question::firstOrNew('some_id', $someId);
$question->fill($request->all()->put('user_id', $user))->save();
Don't forget to fill $fillable array with all properties you want to persist:
class Question extends Model
{
protected $fillable = [
'marital_status',
'job_title',
'industry',
'occupation',
'paye',
'self_employed',
'child_benefit',
'work_home',
'own_transport',
'company_vehicle',
'annual_income',
'pay_memberships',
'income_benefits',
'printer',
'contact',
'share',
'terms',
'user_id'
]
Update
If put() method doesn't work for some reason, try this:
$request->merge(['user_id' => $user]);
And then just use $request->all()
Or:
$requestData = $request->all();
$requestData['user_id'] = $user;
And then use $requestData