I have a db model that looks like:
public CallTrackers()
{
CallTrackerCallerTelns = new HashSet<CallTrackerCallerTelns>();
CallTrackerClients = new HashSet<CallTrackerClients>();
CallTrackerFlwups = new HashSet<CallTrackerFlwups>();
CallTrackerHistory = new HashSet<CallTrackerHistory>();
}
With my GetAll() I am loading everything fine except for CallTrackerClients has 3 nested objects that I can't retrieve:
public CallTrackerClients()
{
CallTrackerClientAdvice = new HashSet<CallTrackerClientAdvice>();
CallTrackerClientOffences = new HashSet<CallTrackerClientOffences>();
CallTrackerClientSureties = new HashSet<CallTrackerClientSureties>();
}
I am trying:
[HttpGet]
public IEnumerable<CallTrackers> GetAll()
{
return _context.CallTrackers
.Include(log => log.CallTrackerClients)
.ThenInclude(c => c.CallTrackerClientAdvice)
.Include(log => log.CallTrackerCallerTelns)
.Include(log => log.CallTrackerFlwups)
.Include(log => log.CallTrackerHistory)
.ToList();
}
The above works but I need to get the Sureties and Offences as well. When I try .ThenInclude(c => c.CallTrackerClientOffences)I get some 'does not contain definition' error.
Any ideas how to get the two remaining collections that are part of CallTrackerClients?
You always have to start from the parent entity.
return _context.CallTrackers
.Include(log => log.CallTrackerClients)
.ThenInclude(c => c.CallTrackerClientAdvice)
// this
.Include(log => log.CallTrackerClients)
.ThenInclude(c => c.CallTrackerClientOffences)
// and this
.Include(log => log.CallTrackerClients)
.ThenInclude(c => c.CallTrackerClientSureties)
.Include(log => log.CallTrackerCallerTelns)
.Include(log => log.CallTrackerFlwups)
.Include(log => log.CallTrackerHistory)
.ToList();
Related
I'm fairly new to Laravel and React. I have 3 tables called students, users and projects. Each project has 1 student, 1 supervisor and 2 examiners (supervisors and examiners are users) assigned to it. I want to try to fetch the names of the student and user from the respective tables and display them.
My Project.php
protected $with =['projectStudent', 'projectSupervisor', 'projectExaminer1', 'projectExaminer2'];
public function projectStudent()
{
return $this->belongsTo('App\Models\Student', 'student_id', 'student_id');
}
public function projectSupervisor()
{
return $this->belongsTo('App\Models\User', 'supervisor_id', 'id');
}
public function projectExaminer1()
{
return $this->belongsTo('App\Models\User', 'examiner1_id', 'id');
}
public function projectExaminer2()
{
return $this->belongsTo('App\Models\User', 'examiner2_id', 'id');
}
My ProjectController.php
public function index()
{
return ProjectResource::collection(
Project::query()->with('projectStudent')->orderBy('id', 'desc')->paginate(5)
);
}
My Projects.jsx
const [projects, setProjects] = useState([]);
const [paginate, setPaginate] = useState(1);
const [loading, setLoading] = useState(false);
const {setNotification} = useStateContext();
useEffect(() => {
getProjects();
}, [paginate])
const handlePaginate = (direction) => {
setPaginate(prevPage => prevPage + direction)
}
function classNames(...classes) {
return classes.filter(Boolean).join(' ')
}
const getProjects = () => {
setLoading(true);
axiosClient.get(`/projects?page=${paginate}`)
.then(({data}) => {
setLoading(false);
setProjects(data.data);
})
.catch(() => {
setLoading(false);
})
}
I want to get name of the student and the names of supervisor and examiner but project.projectStudent.name returns undefined.
When I try to console.log(JSON.stringify(data.data, null, 2)) the data, I get
[
{
"id": 1,
"title": "Stock Market Prediction",
"student_id": "SW0102469",
"supervisor_id": 18,
"examiner1_id": 12,
"examiner2_id": 33
}
]
And this is my projectResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ProjectResource extends JsonResource
{
public static $wrap = false;
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'student_id' => $this->student_id,
'supervisor_id' => $this->supervisor_id,
'examiner1_id' => $this->examiner1_id,
'examiner2_id' => $this->examiner2_id,
// 'start_date' => $this->start_date->format('Y-m-d'),
// 'end_date' => $this->end_date->format('Y-m-d'),
// 'duration' => $this->duration,
// 'status' => $this->status,
];
}
}
I know I can query the db like this:
final invoicesDocsRef = await invoicesRef
.orderBy('invoiceNo', descending: true)
.limit(30)
.get()
.then((value) => value.docs.map((doc) => Invoice.fromSnapshot(doc)));
But I want it paginated cause I dont want to call 200 rows for every user, so this was my next approach:
Future<Iterable<Invoice>> getInvoices(
{required int limit, String? lastDocID}) async {
final invoicesDocsRef = invoicesRef.orderBy('invoiceNo', descending: true);
if (lastDocID == null) {
return await invoicesDocsRef.get().then(
(value) => value.docs.map((doc) => Invoice.fromSnapshot(doc)),
);
} else {
final lastDoc = await invoicesRef.doc(lastDocID).get();
return await invoicesDocsRef.startAfterDocument(lastDoc).get().then(
(value) => value.docs.map((doc) => Invoice.fromSnapshot(doc)),
);
}
}
How this is not ordered at all. I thought single indexs were automatic?
When I pass array() through query it got false but when I pass without array then it show success. How can I pass array according to my code?
public function add_employee_post(Request $request){
try{
$http = new \GuzzleHttp\Client();
$employee_no = $request->employee_no;
$name = $request->name;
$nid = $request->nid;
$dob = $request->dob;
$covid_status = $request->covid_status;
$vaccine_certificate = $request->vaccine_certificate;
$official_email = $request->official_email;
$optional_email = array();
if($request->optional_email[0] != null){
foreach (json_decode($request->optional_email[0]) as $key => $email) {
array_push($optional_email, $email->value);
}
}
$official_phone = $request->official_phone;
$optional_phone = array();
if($request->optional_phone[0] != null){
foreach (json_decode($request->optional_phone[0]) as $key => $phone) {
array_push($optional_phone, $phone->value);
}
}
$designation = $request->designation;
$employee_type = $request->employee_type;
$role = $request->role;
$department = $request->department;
$team = $request->team;
$grade = $request->grade;
$level = $request->level;
$avatar = $request->avatar;
$present_address = $request->present_address;
$permanent_address = $request->permanent_address;
$employee_status = $request->employee_status;
$employee_invitation_status = $request->employee_invitation_status;
$response = $http->post('http://localhost:8000/api/v1/employees/create',[
// 'headers' => [
// 'Authorization' => 'Bearer'.session()->get('token.access_token'),
// ],
'query' =>[
'employee_no' => $employee_no,
'name' => $name,
'nid' => $nid,
'dob' => $dob,
'covid_status' => $covid_status,
'vaccine_certificate' => $vaccine_certificate,
'official_email' => $official_email,
'optional_email' => $optional_email,
'official_phone' => $official_phone,
'optional_phone' => $optional_phone,
'designation' => $designation,
'employee_type' => $employee_type,
'role' => $role,
'department' => $department,
'team' => $team,
'grade' => $grade,
'level' => $level,
'avatar' => $avatar,
'present_address' => $present_address,
'permanent_address' => $permanent_address,
'employee_status' => $employee_status,
'employee_invitation_status' => $employee_invitation_status,
]
]);
$result = json_decode((string) $response->getBody(), true);
return $result;
}
catch(\Throwable $e){
return response()->json([
'result' => false,
'message' => 'Something Error!'
]);
}
}
In same code when I comment out $optional_phone and $optional_email , it show success response but when I pass all then it show false result. How I pass an array inside query?
Up until this morning this problem did not exist. Now, however, when I try to insert into a table with an identity field that is not the primary key I get the above error.
Configuration:
public BidToConfiguration()
{
ToTable("BidTo");
HasKey(bt => new { bt.BidRecipientCode, bt.ProposalNumber });
Property(bt => bt.Awarded)
.IsOptional();
Property(bt => bt.BidRecipientCode)
.IsRequired()
.HasMaxLength(10);
Property(bt => bt.BidValue)
.IsRequired();
Property(bt => bt.ContactEmail)
.IsOptional()
.HasMaxLength(150);
Property(bt => bt.ContactName)
.IsOptional()
.HasMaxLength(150);
Property(bt => bt.ContactPhone)
.IsOptional()
.HasMaxLength(25);
Property(bt => bt.ID)
.IsRequired()
.HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
Property(bt => bt.LastChanged)
.IsRequired();
Property(bt => bt.LastChangedBy)
.IsRequired()
.HasMaxLength(50);
Property(bt => bt.ProposalNumber)
.IsRequired()
.HasMaxLength(15);
Property(bt => bt.ReqForBidNumber)
.IsOptional()
.HasMaxLength(50);
HasRequired(bt => bt.BidRecipient)
.WithMany(br => br.BidTos)
.HasForeignKey(bt => bt.BidRecipientCode);
}
Insert into this table:
BidTo newBidTo = new BidTo();
newBidTo.Awarded = bt.Awarded;
newBidTo.BidRecipientCode = bt.BidRecipientCode;
newBidTo.BidValue = bt.BidValue;
newBidTo.ContactEmail = bt.ContactEmail;
newBidTo.ContactName = bt.ContactName;
newBidTo.ContactPhone = bt.ContactPhone;
newBidTo.ID = bt.ID;
newBidTo.LastChanged = DateTime.Now;
newBidTo.LastChangedBy = User.Identity.Name;
newBidTo.ProposalNumber = proposal.ProposalNumber;
newBidTo.ReqForBidNumber = bt.ReqForBidNumber;
_dbpm.BidTos.Add(newBidTo);
When I execute the context.SaveChanges() I get the error regardless if I have the line "newBidTo.ID = bt.ID;" commented out or not.
ADDED: One note, this table, but not the other two with the same error has an INSERT/UPDATE/DELETE Trigger.
I'm currently using DB-Transaction and it throws Lexical variable error
attached here is my code:
DB::transaction(function ($request) use ($request) {
$salesman = new Salesman([
'operation_id' => $request->get('operation_id'),
'warehouse_id' => $request->get('warehouse_id'),
'salesman_name' => $request->get('salesman_name'),
'address' => $request->get('address'),
'contact_number' => $request->get('contact_number'),
'email_address' => $request->get('email_address'),
'area_id' => 'pending',
]);
$salesman->save();
});
return view('salesman.index');
}
It is working now after I remove the $request parameter in function
DB::transaction(function () use ($request) {
$salesman = new Salesman([
'operation_id' => $request->get('operation_id'),
'warehouse_id' => $request->get('warehouse_id'),
'salesman_name' => $request->get('salesman_name'),
'address' => $request->get('address'),
'contact_number' => $request->get('contact_number'),
'email_address' => $request->get('email_address'),
'area_id' => 'pending',
]);
$salesman->save();
});
return view('salesman.index');
}