i have a model request that has a foreign key to category and a collection of buyers
class Request extends Model {
// TABLE NAME
protected $table = 'requests';
// MASS ASSIGMENTS
protected $guarded = ['id'];
// FK
public function category()
{
return $this->hasOne('App\Objects\Category', 'id');
}
// FK
public function buyers()
{
return $this->hasMany('App\Objects\RequestBuyer');
}
}
i have a query that get's all request records with the collection of buyers
$requests = Request::with('buyers')->get();
this return a json that contains all records with the collection of buyers but i want to include the category details in this json response.
How do i accomplish this?
do as following,
$requests = Request::with('buyers', 'category')->get();
By the way what is the relationship between Request and Category?
Related
Current laravel models relations: ParentModel can have many documents, ChildModel can have many documents, same Documents can be belonged to any of ParentModel and ChildModel.
Also ChildModel always belongs to one ParentModel. ParentModel can have multiple ChildModels.
App\ParentModel relationships
...
public function childmodels()
{
return $this->hasMany('App\ChildModel');
}
public function documents()
{
return $this->morphToMany('App\Document', 'documentable');
}
...
App\ChildModel relationships
...
public function parentmodel()
{
return $this->belongsTo('App\ParentModel');
}
public function documents()
{
return $this->morphToMany('App\Document', 'documentable');
}
...
App\Document
...
public function parentmodels()
{
return $this->morphedByMany('App\ParentModel','documentable');
}
public function childmodels()
{
return $this->morphedByMany('App\ChildModel','documentable');
}
...
Now I'm trying to get all records of ChildModels (1) which have documents with specific type and (2) its ParentModel can also have documents.
The (1) first goal can be reached with such ChildModel method.
/* checking GET param to join this condition to final query */
if($request->has('report') && $request->input('report') == 'on') {
/* get all documents related to CurrentModel */
$query->whereHas('documents',function (Builder $query) {
$query->where('type', 1);
});
}
But this obviously doesnt include records of ChildModels, ParentModel of which has documents with specific type.
So the question is: how to include such condition into ChildModel query builder?
Found the easy way to access relations in builder
$query->whereHas('parentmodels.documents', function(Builder $query){
$query->where('type',1);
});
I want to ask about how to retrieve all data in laravel
I have tables like this
Corp
corp_id
corp_name
Subsidiary
subsidiary_id
corp_id
subsidiary_name
Customer PIC
cust_pic_id
corp_id
subsidiary_id
cust_name
cust_phone
cust_address
cust_email
Each model like this
corp model
protected $table= 'corps';
public function CustomerPIC()
{
return $this->hasMany('App\CustomerPIC');
}
subsidiary model
protected $table = 'subsidiaries';
public function CustomerPIC()
{
return $this->hasMany('App\CustomerPIC');
}
customer PIC model
protected $table = 'customer_P_I_CS';
public function corp()
{
return $this->belongsTo('App\Corp');
}
public function subsidiary()
{
return $this->belongsTo('App\Subsidiary');
}
and I have a controller
public function getCustomer()
{
$getData = CustomerPIC::with(['Corp','Subsidiary'])->get();
return response()->json([
'data'=>$getData
]);
}
The question is, why I get the return without corp_name and subsidiary_name. and there is corp:NULL and subsidiary: NULL even I don't have that row
Which is there is no corp_name and subsidiary_name?
I want to return all of data.
Thank you for read it
Make sure you load relationships with lowercase (same as you defined relationships):
$getData = CustomerPIC::with(['corp','subsidiary'])->get();
I have three models Class, Students and Studentinfo. Class and students are in a One to Many relationship and Sudents and studentinfo are in a one to one relationship.
While getting students from certain Class I get a list of data in an array.
What is the best way to get data from studentinfo for each student in the array?
I am trying to get this data in json format.
You'd set up relationships like the following on the models, the important one being the hasManythrough relation:
// Class.php
public function students() {
return $this->hasMany(Student::class);
}
public function studentInfo()
{
return $this->hasManyThrough(StudentInfo::class, Student::class);
}
// Student.php
public function studentInfo() {
return $this->hasOne(StudentInfo::class);
}
public function classes() {
return $this->belongsToMany(Class::class);
}
// StudentInfo.php
public function student() {
return $this->belongsTo(Student::class);
}
... you may cast a model or collection to a string, which
will automatically call the toJson method on the model or collection:
$json = (string)$class->studentInfo;
Laravel Docs: Serialization
So i've got two models, Client and Project, and Client has a hasMany relationship with projects. I'm just trying to add the project count for the client into the JSON response but I can't get it to work.
My controller just returns all the projects;
public function index(Client $client)
{
return $client->all();
}
And my model contains the below;
protected $appends = ['client_projects_count'];
/**
* Create a relationship between this client and it's projects
*/
public function clientProjects() {
return $this->hasMany('App\Project');
}
public function getClientProjectsCountAttribute()
{
return $this->withCount('clientProjects');
}
This just adds client_projects_count to the response but it's an empty array. I'm close, if I dd($this->withCount('clientProjects')->get()) I can see the client_projects_count with the correct count, but if I remove the dd and keep the ->get() then I get an internal server error.
Also, it is possible to only load this for the index() method rather than every one?
From the Documentation
$clients = Client::withCount('projects')->get();
foreach ($clients as $client) {
echo $client->projects_count;
}
So I managed to resolve it myself, although I'm sure their must be a nicer way.
Client.php
protected $appends = ['client_projects_count'];
/**
* Create a relationship between this client and it's projects
*/
public function clientProjects() {
return $this->hasMany('App\Project');
}
public function clientProjectsCount()
{
return $this->clientProjects()->selectRaw('client_id, count(*) as aggregate')->groupBy('client_id')->get();
}
public function getClientProjectsCountAttribute()
{
return isset($this->clientProjectsCount()[0]) ? $this->clientProjectsCount()[0]->aggregate : 0;
}
I am having problem with Laravel Eloquent relations i understand how they work but i dont know how to "use" them properly, so i need some guidance/pointers.So here goes.
I have Exam table
Schema looks like (thanks to lukasgeiter)
exams
id
title
duration
questions
id
text
exam_id
answers
id
text
question_id
correct (boolean)
Relations:
Exam Model
public function questions(){
return $this->hasMany('Question');
}
Question Model
public function answers(){
return $this->hasMany('Answer');
}
public function exam(){
return $this->belongsTo('Exam');
}
Answer Model
public function question(){
return $this->belongsTo('Question');
}
And i understand this part but now i want users to be able to solve exam and store that data (i need to save an answer from user, for example user_id 1, exam_id 2, question_id 1, answer true). i have done it this way but i think its wrong (Yeah it does work but i dont think its the right way)
Schema looks like
Users
id
email
pass
...
SolvedExams
id
user_id
exam_id (havent put relation here not sure if needed)
solved (boolean) // if its completed right or wrong
SolvedQuestions
id
exam_id (havent put relation here not sure if needed)
answer(boolean)(then later i check this boolean with answers) //if the answer is right or wrong
Now with relations i have done same as i said before
User Model
public function SolvedExams() {
return $this->hasMany('SolvedExams');
}
SolvedExam model
public function User() {
return $this->belongsToMany('User');
}
public function questions() {
return $this->hasMany('solved');
}
SolvedQuestions model
public function exam() {
return $this->belongsTo('SolvedExam');
}
Is this the right way or am i doing it wrong (and I am a begginer with relations)
I think you are pretty close...
I'd do it this way:
Tables
exams
id, title, duration
questions
id, text, exam_id
answers
id, text, question_id, correct
users
id, email, password
tries
id, user_id, exam_id
answers_try (pivot table)
id, try_id, answer_id
Relations
Exam
public function questions(){
return $this->hasMany('Question');
}
public function tries(){
return $this->hasMany('Try');
}
Question
public function answers(){
return $this->hasMany('Answer');
}
public function exam(){
return $this->hasMany('Exam');
}
Answer
public function question(){
return $this->belongsTo('Question');
}
public function tries(){
return $this->belongsToMany('Try');
}
User
public function tries(){
return $this->hasMany('Try');
}
Try
public function answers(){
return $this->belongsToMany('Answer');
}
public function user(){
return $this->belongsTo('User');
}
public function exam(){
return $this->belongsTo('Exam');
}
Usage
Get the users answer for a question
$answer = User::find(1)
->tries()->where('exam_id', 2)->first()
->answers()->where('question_id', 3)->first();
Creating a new exam
$exam = new Exam;
$exam->save();
$question = new Question;
$question->text = 'Foo?';
$exam->questions()->save($question);
$answer1 = new Answer;
$answer1->text = 'Foo!';
$answer1->correct = true;
$answer2 = new Answer;
$answer2->text = 'Bar!';
$answer2->correct = false;
$question->answers()->saveMany([$answer1, $answer2]);
Saving users answer
$exam = Exam::find(1);
$user = Auth::user();
$try = new Try;
$try->user()->associate($user)->save();
$exam->tries()->save($try);
$try->answers()->attach(2); // 2 is the answer id