How can I retrieve data from a foreignID - javascript

I am new to laravel and I am struggling to retrieve data using the query Builder.
Consider the following migration on the Hotel table:
$table->id();
$table->timestamps();
$table->foreignIdFor(User::class);
$table->foreignIdFor(Room::class);
Now consider that I have in my HotelController:
$hotel = Auth::user()->hotels which retrieves this on dd:
[{"id":1, "user_id":51,"room_id":11, "booking_id":7}
[{"id":2, "user_id":51,"room_id":16, "booking_id":21}
[{"id":3, "user_id":51,"room_id":18, "booking_id":44}
[{"id":4, "user_id":51,"room_id":45, "booking_id":33}
I now want to retrieve the data from each of the room_id and booking_id from each of the Auth users which in this case is user 51. Can anyone help me with how can I achieve this?
Thank you in advance

Assuming you defined the relationships (belongsTo, hasOne, hasMany, etc) in the models for Hotel, Room and Booking, you can just iterate through the list of hotels getting each hotel into a $hotel local variable, and asking for their related models information like this:
foreach ($hotels as $hotel) {
$hotel->room // gets you the related room
$hotel->booking // gets you the related booking
}

Related

Ruby on Rails Active record object

I have a User model and having has_many associations with Note model.
Getting the records in an array format. I have to show content(column of note model) only.
So, Fetching data using:
#user.notes.pluck(:content).
It is giving like this.
["Testing Notes123", "Testing Notes12345"].
In UI I want to display like this:
Testing Notes123
Testing Notes12345
Could someone please help me to fix this.
By the "UI" do you mean a web page? That would involve a controller and a view. If you're just talking about the console, then this should do it:
notes = #user.notes.pluck(:content)
notes.each do |note|
puts note
end
Or:
notes = #user.notes.pluck(:content)
puts notes.join("\n")

Formatting data from Firebase with HTML and CSS

This time I'm facing a problem with formatting data from Firebase. This is how structure in my database looks:
I'm getting it from database using this code:
const preObject = document.getElementById('object')
var parametryObject = firebase.database()
.ref('Parametry_powietrza')
.limitToLast(1)
.once('value').then(function(snapshot) {
var listaParametrow = snapshot.val();
console.log(listaParametrow);
preObject.innerText = JSON.stringify(snapshot.val(), null, 3)
});
And on my webpage it looks like:
My question is - how to properly refer to that data to be able to change its appearance using HTML and CSS?
Thank you! :)
It looks like you're trying to access the data inside your JSON object being returned to you from your FireBase RealTime database (RTDB). But the way you've structured your data makes it near impossible for your javascript to iterate through it.
Some pointers I can give you regarding your data in the Realtime Database atm:
1) Datetime is typically stored in what's called Epoch Time. Which is typically the number of seconds since Jan 1, 1970. The number can easily be converted back into text using various javascript time libraries. An easy one to try out is Luxon. You can see epoch time with this online convertor here.
2) Secondly, RTDB supports the creation of unique, sequential, sortable "push-id" whenever you call the .push({ myDataObject }) function. So there's no need to store the date and the time as the "keys" to your object. More info about the push-id here and here. It's really interesting stuff!
3) I hate to be writing this suggestion because it seems like taking a step back before you can take steps forward, but I feel like you would benefit alot on looking at some articles on designing databases and how to sensibly structure your data. Firebase also has a great introduction here. If it's any help, for your data structure, I suggest modifying your data structure to something like below:
{
Parametry_powietrza: {
[firebase_push_id]: {
timestamp: 726354821,
Cisnienie: 1007.78,
Temperatura: 19.23,
Wilgotnosc: 52.00,
},
[firebase_push_id]: {
timestamp: 726354821,
Cisnienie: 1007.78,
Temperatura: 19.23,
Wilgotnosc: 52.00,
}
}
}
That way, when firebase returns your data, you can iterate through the data much more easily and extract the information you need like:
database
.ref('Parametry_powietrza')
.limitToLast(10)
.once('value', snapshot => {
snapshot.forEach(child => {
// do what you need to do with the data
console.log("firebase push id", child.key);
console.log("data", child.val());
})
});
All the best! BTW are you using any javascript frameworks like React or Vue?

What is the best practice when displaying data from more than one table

I have three tables, 'sessions', 'classes' and 'schedules' which they are connected each other.
sessions: id, name, descr
classes: id, session_id, name
schedules: class_id, session_id, date
A class belongs to a session, while the schedules is a N:M relations which gives the opportunity to have particular date for each session within a single class.
My problem comes when I have to display these information, I have a function which displays all Sessions:
$sessions = Session::all();
and I have another function which displays the date of a specific class and a specific session as below:
$result = Schedule:where('class_id','=',$classId)->where('session_id','=',$essionId)->first();
So let say I have 30 sessions for a single class, when it comes to my front-end app which is written in AngularJS I dont know how to handle the displaying here using the ng-repeat iterating thru all sessions and then make another call withing the ng-repeat iteration to call the schedule to display the date of the session, this is not a good practice I guess in AngularJS.
Could anyone tell me what would be the best option for me to handle this problem? Shall I have to modify the back-end? like edit the Session:all(); query to include also the Schedule table? or what is the best way?
I supposed you have already config your relations in models, if not look here
As for me, I use Fractal to customize display data. Also there is convenient method called Available includes
So you can request your data like /sessions/?include=classes and get output
{data: [{
session_id: 1,
some: "data",
classes:[{
class_id: 11,
some: "class_data"
}]
}]}
I would "eager load" the data, so you can access all the object's parents through the object you loaded. This way you can fill your table rows one by one by just iterating over 1 object.
There is excellent documentation about eager loading at the Laravel website, so I suggest you start there

How do I pull rows from mysql with Javascript onchange

I have a website where info of registered member from various countries and states are collected. On my search form, I have 3 fields; Country, State and Sex.
I listed all the countries of the world in my search (as a dropdown), but the state field is empty. Want I want is that once a visitor select a country, i want only the states of that country which registered members have are in my database to be pulled into the state field, instead of all the state of that country.
Eg 3 members from USA are from New York, New Jersey and Georgia. On selecting USA in the country dropdown, only these 3 state should appear under the state instead of the 50 states in america.
You would need to do a script, for example, in php(or any server side language), that does the query, it would look like:
$countryId = $_POST['countryId'];
$sql = "SELECT fields FROM states WHERE countryId = $countryId";
$result = .... etc;
returning an json object for example to the main page.
And from the main page you should do a Ajax request to the php page, getting the json object returned depending on your option selected and populating the next field.
You could have a look at jQuery framework as at least I, find easier than using raw javascript.
You could pull the the states of the registered members from your database using php or any server-side language you are using. Then you can use AJAX to get the states as an xml or a JSON object. You can the use the members of the object to populate the dropdown.
Example sql query string to get states of registered users: Select state From user_details WHERE country = 'USA'. This should return the states (probably in an array);
Example PHP code that will be retrieved by an AJAX call: $reply = {states: [NJ, NY, AZ]}.
Example JS code to parse the above reply: var reply = JSON.parse(serverReply);
var states = reply.states;
. I hope this helps

Get full data set, sorted with YUI Data Table with Pagination

I hope I am describing my issue enough.. here goes:
I have a YUI data table, get a server side set of records via JSON, and then populates the data.
Users can click on the headers to sort the data in three of the 6 columns, (which are using a custom sort function for each column). The sorting is done client-side.
When a user sorts the data, I need to be able to get a complete list of the values from one of the columns being shown. I need all the data available, not just what's rendered to the page. The data hidden via pagination must be included.
Any ideas? I've tried the handleDataReturnPayload and doBeforeLoadData methods of the DataTable but both give the original, unsorted data.
I'm really stuck here and I've got a client depending on a feature that depends on me getting this sorted list.
Thanks in advance.
Satyam, over at the YUI Forums answered my question perfectly.
The data is actually stored in the
RecordSet. At any time you can go and
look at it, and it will be sorted as
shown on the screen, but it will have
all the data, whether shown or not.
Method getRecordset() will give you a
reference to it and then you can loop
through its records.
You can listen to the columnSortEvent
to be notified a sort has occurred.
I just subscribed to the columnSortEvent event and looped through the array returned by datatable.getRecordSet().getRecords().
I'd recommend posting this to the YUI forums -- http://yuilibrary.com/forum/ -- that's a great place to get support on DataTable issues.
I stumbled upon this question looking for information on how to retrieve information from a dataset that was NOT displayed in the datatable. IF you place the hidden data in the datasource before any field you wish to be displayed, it will be rendered blank, but if you place it after your last field that will be rendered (as defined by the columns object), then they will not render but still be accessible through the record).
var columns = [
{key:"Whatchamacallits", children:[
{key:"name" },
{key:"price" }
]}
];
var ds = new YAHOO.util.DataSource('index.php...');
oDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
oDataSource.responseSchema = {
fields:["name","price","id"]
};
var dt = new YAHOO.widget.DataTable("dt-id", columns, ds, {});
dt.subscribe("rowClickEvent", dt.onEventSelectRow);
dt.subscribe("rowSelectEvent", function(p){ alert(p.getData('id'); });

Categories

Resources